在模块上使用sinon测试方法调用.出口的方法
Testing for method calls using sinon on module.exports methods
我正在尝试测试是否在特定条件下使用摩卡,chai和sinon调用特定方法。下面是代码:
function foo(in, opt) {
if(opt) { bar(); }
else { foobar(); }
}
function bar() {...}
function foobar() {...}
module.exports = {
foo: foo,
bar: bar,
foobar:foobar
};
下面是我的测试文件中的代码:
var x = require('./foo'),
sinon = require('sinon'),
chai = require('chai'),
expect = chai.expect,
should = chai.should(),
assert = require('assert');
describe('test 1', function () {
it('should call bar', function () {
var spy = sinon. spy(x.bar);
x.foo('bla', true);
spy.called.should.be.true;
});
});
当我在spy上执行console.log时,它说它没有被调用,即使在bar方法中手动登录,我也能看到它被调用。有什么建议,我可能做错了或如何去做?
谢谢
您已经创建了一个spy
,但是测试代码没有使用它。用spy替换原来的x.bar
(不要忘记做清理!)
describe('test 1', function () {
before(() => {
let spy = sinon.spy(x.bar);
x.originalBar = x.bar; // save the original so that we can restore it later.
x.bar = spy; // this is where the magic happens!
});
it('should call bar', function () {
x.foo('bla', true);
x.bar.called.should.be.true; // x.bar is the spy!
});
after(() => {
x.bar = x.originalBar; // clean up!
});
});
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- D3在一个调用中绘制不同的SVG形状,没有可见性
- 如何从Java/scala调用js美化程序
- 如何调用这个匿名 JavaScript 函数
- 如何从模块链中调用函数.导出到节点中
- 我需要从php调用javascript或jquery
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 单击按钮后如何逐个调用分区,上一个分区将隐藏
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- node.js:setInterval()正在跳过调用
- 如何在单击复选框后调用控制器方法
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 使用Google Visualization动态调用构造函数
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 调用函数内部的函数
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- Javascript/jQuery中的并行Ajax调用
- 在模块上使用sinon测试方法调用.出口的方法