我似乎无法让以下集成测试通过使用 mocha 、 supertest 和 should (和 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'
显然,应用程序代码没有做任何有用的事情。我只是想通过考试。
将期望 (res.text.should.include('logged in')
) 放在 end 函数之外和 expect
函数内会产生相同的结果。我还尝试了函数调用的变体,例如删除 .type('form')
调用,并使用 .send(user: 'username', password: 'password ')
而不是两个 .field()
调用。
如果这意味着什么,当应用在本地运行时向应用发送 curl POST 请求会产生相同的输出(临时移动。重定向到//127.0.0.1:3456/login
)
我觉得这是一个微不足道的错误。可能是我在应用程序代码或测试代码中忘记了一些东西。
有什么建议吗?
编辑 1: 还值得注意的是,在浏览器中单击提交按钮时,我得到了预期的结果(一条消息)。
编辑 2: 进一步调查显示 any 重定向结果在 Moved Temporarily 中的输出。重定向到 ...
响应正文。这让我想知道我在 app.js 中导出应用程序的方式是否存在问题。
var express = require('express')
var app = express();
module.exports = app;
最佳答案
在 supertest
中有内置的断言:
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)
关于node.js - 测试在 Node 中使用 mocha/supertest 重定向的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272228/