[英]Jasmine-node - Creating a spy on a constructor called inside other function
[英]How to spy on a method inside a dependent module using jasmine-node
我正在尝试为模块“(说”模块A)“需要”另一个模块(“模块B”)编写茉莉花测试。
======> moduleB.js
function moduleBFunction(){
console.log('function inside moduleB is called');
}
======> moduleA.js
var moduleB = require('./moduleB');
function moduleAfunction(input){
if(input){
moduleB.moduleBFunction()
}
}
我想编写一个茉莉花测试用例,在我调用moduleAfunction时进行测试,是否调用moduleBfunction。 我试图使用spyOn()编写测试。 但是我不确定如何在依赖模块中模拟方法。 我做了一些研究,发现我可以为此目的使用“重新接线”模块,如下所示
var moduleB = require('../moduleB');
moduleB.__set__('moduleBfunction', moduleBfunctionSpy);
moduleA.__set__('moduleB', moduleB);
it('should call moduleBfunction', function(){
moduleA.moduleAfunction()
expect(moduleB.moduleBfunction()).toHaveBeenCalled()
});
但我觉得应该有一个更简单的方法。
请提出建议。
我推荐sinon.js
var sinon = require('sinon')
var moduleA = require('../moduleA')
var moduleB = require('../moduleB')
it('should call moduleBfunction', function() {
var stub = sinon.stub(moduleB, 'moduleBfunction').returns()
moduleA.moduleAfunction()
expect(moduleB.moduleBfunction.calledOnce)
stub.restore()
})
您可以轻松地伪造许多不同的行为,例如:
在执行下一个测试之前,请不要忘记还原每个存根。 最好使用沙盒和afterEach / beforeEach
describe('tests which require some fakes', function() {
var sandbox
beforeEach(function() {
sandbox = sinon.sandbox.create()
})
afterEach(function() {
sandbox.restore()
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.