我有一个像这样的javascript函数:
var otherModule = require('../otherModule');
function myFn(req, res, next) {
otherModule.queryFunction()
.then(function(results) {
res.json(results);
})
.catch(function(err)) {
res.json({
err: err
});
});
}
为了测试myFn
功能,我在单元测试中嘲笑(使用mockery)otherModule.queryFunction
,以便返回一些已知结果。在myFn
单元测试中,我想测试是否正在调用res.json
。我知道如果我正在测试otherModule.queryFunction
我可以通过返回promise或将done
参数传递给spectation函数来实现。但是,如果异步部分位于由测试功能调用的函数内部,我无法弄清楚如何进行异步测试。
我尝试过这种方法但没有成功:
'use strict';
var chai = require('chai');
var mockery = require('mockery');
var expect = chai.expect;
var spies = require('chai-spies');
var myFn = require('path/to/myFn');
chai.use(spies);
describe('myFn tests', function (){
var otherModule;
var SOME_DATA = {data: 'hi'};
beforeEach(function (){
otherModule = {
queryFunction: function queryFunctionMock(){
var promise = new Promise(function(resolve, reject){
resolve(SOME_DATA);
});
return promise;
}
};
});
beforeEach(function (){
mockery.enable({
warnOnReplace: false,
useCleanCache: true
});
mockery.registerMock('../otherModule', otherModule);
});
afterEach(function (){
mockery.disable();
});
it('res.json should be called with otherModule.queryFunction results', function (){
req = chai.spy();
res = chai.spy.object(['json']);
next = chai.spy();
myFn(req, res, next);
expect(res.json).to.have.been.called();
});
});
答案 0 :(得分:2)
我认为唯一不对的是,您需要移动正在测试的组件的需求,在之后初始化mock:
'use strict';
var chai = require('chai');
var mockery = require('mockery');
var expect = chai.expect;
var spies = require('chai-spies');
var myFn;
chai.use(spies);
describe('myFn tests', function (){
// [...]
beforeEach(function (){
mockery.enable({
warnOnReplace: false,
useCleanCache: true
});
mockery.registerMock('../otherModule', otherModule);
// now load the component:
myFn = require('path/to/myFn');
});