testing在节点中使用mocha / supertestredirect的请求

我似乎无法得到以下的集成testing,通过使用摩卡 , supertest , 应该 (和coffeescript)的快速项目。


考试

should = require('should') request = require('supertest') app = require('../../app') describe 'authentication', -> describe 'POST /sessions', -> describe 'success', (done) -> it 'displays a flash', (done) -> request(app) .post('/sessions') .type('form') .field('user', 'username') .field('password', 'password') .end (err, res) -> res.text.should.include('logged in') done() 

相关的应用程序代码

 app.post '/sessions', (req, res) -> req.flash 'info', "You are now logged in as #{req.body.user}" res.redirect '/login' 

失败

 1) authentication POST /sessions success displays a flash: AssertionError: expected 'Moved Temporarily. Redirecting to //127.0.0.1:3456/login' to include 'logged in' 

显然,应用程序代码没有任何用处。 我只是想让testing通过。

将期望值( res.text.should.include('logged in') )放在end函数的外部,并在expect函数内部产生相同的结果。 我也尝试了函数调用的一个变种,例如删除.type('form')调用,并使用.send(user: 'username', password: 'password')而不是两个.field()调用。

如果这意味着什么,当它在本地运行时向应用发送curl POST请求会产生相同的输出( Moved Temporarily. Redirecting to //127.0.0.1:3456/login

我有一种感觉,这是一个微不足道的错误。 可能是我在应用程序代码或testing代码中忘记的东西。

有什么build议么?

编辑1:还值得注意的是,当点击浏览器中的提交button时,我得到了预期的结果(一个flash消息)。

编辑2:进一步调查显示在Moved Temporarily. Redirecting to ... 任何redirect结果的输出Moved Temporarily. Redirecting to ... Moved Temporarily. Redirecting to ...响应身体。 这让我怀疑在app.js中导出应用程序的方式是否有问题。

 var express = require('express') var app = express(); module.exports = app; 

对于遇到这个页面的人来说,这个问题的答案很简单。 Moved Temporarily. 响应体是从超级归来的。 看到问题的更多细节。

总而言之,我最终做了这样的事情。

 should = require('should') request = require('supertest') app = require('../../app') describe 'authentication', -> describe 'POST /sessions', -> describe 'success', -> it 'redirects to the right path', (done) -> request(app) .post('/sessions') .send(user: 'username', password: 'password') .end (err, res) -> res.header['location'].should.include('/home') done() 

只要检查响应标题的location是你所期望的。 testingFlash消息并查看特定的集成testing应该使用另一种方法。

这里有超内置的断言:

 should = require('should') request = require('supertest') app = require('../../app') describe 'authentication', -> describe 'POST /sessions', -> describe 'success', -> it 'redirects to the right path', (done) -> request(app) .post('/sessions') .send(user: 'username', password: 'password') .expect(302) .expect('Location', '/home') .end(done) 

我正在尝试为redirect的请求编写一些集成testing,并在这里find了本模块作者的一个很好的例子。

在TJ的例子中,他使用链接,所以我也使用了类似的东西。

考虑一种login用户在注销时redirect到主页的情况。

 it('should log the user out', function (done) { request(app) .get('/logout') .end(function (err, res) { if (err) return done(err); // Logging out should have redirected you... request(app) .get('/') .end(function (err, res) { if (err) return done(err); res.text.should.not.include('Testing Tester'); res.text.should.include('login'); done(); }); }); }); 

根据你有多lessredirect,你可能需要嵌套一些callback,但TJ的例子应该足够了。