[英]How to spy on a method inside a dependent module using jasmine-node
I am trying to write jasmine tests for a module-(say moduleA) which 'requires' another module-(moduleB). 我正在尝试为模块“(说”模块A)“需要”另一个模块(“模块B”)编写茉莉花测试。
======> moduleB.js ======> moduleB.js
function moduleBFunction(){
console.log('function inside moduleB is called');
}
======> moduleA.js ======> moduleA.js
var moduleB = require('./moduleB');
function moduleAfunction(input){
if(input){
moduleB.moduleBFunction()
}
}
I want to write a jasmine test case that tests when i call moduleAfunction, is it calling moduleBfunction or not. 我想编写一个茉莉花测试用例,在我调用moduleAfunction时进行测试,是否调用moduleBfunction。 I tried to write a test using spyOn().
我试图使用spyOn()编写测试。 but i am not sure how can i mock a method inside a dependent module.
但是我不确定如何在依赖模块中模拟方法。 I did some research and found i might be able to use 'rewire' module for this purpose like below
我做了一些研究,发现我可以为此目的使用“重新接线”模块,如下所示
var moduleB = require('../moduleB');
moduleB.__set__('moduleBfunction', moduleBfunctionSpy);
moduleA.__set__('moduleB', moduleB);
it('should call moduleBfunction', function(){
moduleA.moduleAfunction()
expect(moduleB.moduleBfunction()).toHaveBeenCalled()
});
but I feel there should be a simpler way. 但我觉得应该有一个更简单的方法。
Please suggest. 请提出建议。
I recommend sinon.js 我推荐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()
})
You can easily fake many different behaviours like: 您可以轻松地伪造许多不同的行为,例如:
Don't forget to restore each stub before executing the next test. 在执行下一个测试之前,请不要忘记还原每个存根。 It's best to use sandboxes and afterEach / beforeEach
最好使用沙盒和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.