我正在尝试使用server.inject测试hapijs
/// <reference path="../../typings/index.d.ts" />
import * as chai from "chai";
let assert = chai.assert;
import server from "../../src/server";
import UserController from '../../src/controllers/userController';
import UserRepository from '../../src/libs/repository/mongo/userRepository';
import {IUser, IUserActivation, IUserCreate} from "../../src/libs/repository/interfaces";
describe("routes/user", function() {
const userController = new UserController(server, new UserRepository());
// ========================== [ ACTIVATE ] ==========================
it.only("/activate: should activate a user", function(done) {
let user: IUserActivation = {
'_id': '1234566737465',
'token': '123234523542345'
};
let url = '/api/users/' + user._id + '/' + user.token;
const request = {
method: 'PUT',
url: url,
payload: user
};
server.inject(request).then((response) => {
let res = JSON.parse(response.payload);
//assert.strictEqual(res.success, true, '/users/{id}/{token}')
chai.expect(res.success).to.deep.equal(false);
chai.expect(res.success).to.deep.equal(true);
done();
}).catch((error) => {
console.log(error.message);
});
});
});
response.success属性为true。因此,通常测试应该因chai.expect(res.success).to.deep.equal(false);
而失败。
但测试失败并显示消息:Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
删除catch子句时,它也会因超时错误而失败。
如果我在catch-clause的末尾添加done(),则测试正在通过。这是错误的行为,因为测试应该失败。
如何才能获得预期的行为?提前谢谢。
答案 0 :(得分:1)
问题是server.inject会返回一个promise。只要您使用最新版本的Mocha,它就可以处理,但您不必担心调用done()而是返回server.inject。
describe("routes/user", function() {
const userController = new UserController(server, new UserRepository());
// ========================== [ ACTIVATE ] ==========================
it.only("/activate: should activate a user", function() { //No done needed
let user: IUserActivation = {
'_id': '1234566737465',
'token': '123234523542345'
};
let url = '/api/users/' + user._id + '/' + user.token;
const request = {
method: 'PUT',
url: url,
payload: user
};
//Return the promise
return server.inject(request).then((response) => {
let res = JSON.parse(response.payload);
//assert.strictEqual(res.success, true, '/users/{id}/{token}')
chai.expect(res.success).to.deep.equal(false);
chai.expect(res.success).to.deep.equal(true);
}); //No catch needed.
});
});