这段代码的测试(下面)失败了:
module.exports = function(User, jwt) {
'use strict';
return function(req, res) {
User.create(req.body)
.then(function(id) {
var token = jwt.sign({id: id});
res.json({token: token});
});
};
};
以下是测试:
'use strict';
var chai = require('chai');
var sinon = require('sinon');
require('sinon-as-promised');
chai.should();
chai.use(require('sinon-chai'));
describe('routes/signup', function() {
var User;
var request;
var response;
var jwt;
var signup;
beforeEach(function() {
User = {create: sinon.stub()};
request = {body: 'body'};
response = {json: sinon.spy()};
jwt = {sign: sinon.stub().withArgs({id:'id'}).returns('token')};
signup = require('../../../routes/signup')(User, jwt);
});
it('returns token when resolving', function() {
User.create.resolves('id');
signup(request, response);
return response.json.should.have.been.calledWith({token: 'token'});
});
});
如果我询问了response.json方法,它似乎从未被调用过。 response.args是一个空数组。
我猜我错过了测试承诺的基本内容。救命啊!
答案 0 :(得分:2)
记住promises是异步的,所以你需要等到promise解析,然后调用then
方法来做你的断言。 fr0609的回答会给你一个误报,因为它会在调用then
块之前返回。
试试这个:
it('returns token when resolving', function(done) {
User.create.resolves('id');
signup(request, response)
.then(function() {
response.json.should.have.been.calledWith({token: 'token'});
done();
})
.catch(done);
});