我正在使用 Node.js 和 Restify 构建一个 API。我正在尝试使用 Supertest 和 Tape 进行功能端点测试。我有一个测试对 API 进行两次连续调用,它说我无法在发送标头后设置标头。
用户控制器.js
/*
* Create a user.
*/
exports.store = function(req, res, next) {
// Get request input.
var firstName = ParsesRequest.getValue(req, 'firstName'),
lastName = ParsesRequest.getValue(req, 'lastName'),
email = ParsesRequest.getValue(req, 'email'),
password = ParsesRequest.getValue(req, 'password');
// Create command.
var command = new CreateUserCommand(firstName, lastName, email, password);
// Execute command.
CommandBus.execute(command, function(error, data) {
var hasError = !!error && !data,
status,
message;
status = (!hasError) ? StatusCodes.Created : StatusCodes.InternalServerError;
message = (!hasError) ? UserTransformer.transform(data) : error;
res.json(status, message);
});
}
创建UserApiTest.js
var test = require('tape');
var CreatesFakeUser = require('../../helpers/CreatesFakeUser');
var request = require('supertest');
var config = require('../../../config/Config').getConfiguration('test');
var url = 'http://' + config.url + ':' + config.port;
test('Creates two users with same email and returns error', function(assert) {
var user = CreatesFakeUser.generate();
request(url)
.post('/user')
.set('Accept', 'application/json')
.send(user)
.expect(201)
.end(function(err, res){
assert.equals(res.status, 201, 'Returns 201 as status code.');
assert.equals(!!res.body.id, true, 'Result body has an id field.');
});
request(url)
.post('/user')
.set('Accept', 'application/json')
.send(user)
.expect(500)
.end(function(err, res){
assert.equals(res.status, 500, 'Returns 500 because user already exists.');
assert.end();
});
});
有谁知道为什么第二个请求失败了?我只在我的方法中发送 res.json 一次,所以它似乎不应该设置标题两次。另外,我不确定它是否与将标题上的 Connection 设置为关闭有关,但我试过了,但没有帮助。也许它与异步有关。
任何帮助,将不胜感激!