javascript Mocha 测试模拟功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31725098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mocha tests mocking function
提问by Wizard
I'm testing backbone view, that have function:
我正在测试具有以下功能的主干视图:
attachSelect: function(id, route) {
console.log(id);
console.log(route);
this.$(id).select2({
ajax: {
url: route,
dataType: 'json',
results: function(data) {
var results = _.map(data, function(item) {
return {
id: item.id,
text: item.title
};
});
return {
results: results
};
},
cache: true
}
});
}
I need to rewrite (mock) this fuction that, the looks like:
我需要重写(模拟)这个功能,看起来像:
attachSelect: function(id, route) {
console.log(id);
console.log(route);
}
How to do that ?
怎么做 ?
回答by ssube
The simplest way to mock a function is to replace the property at runtime.
模拟函数的最简单方法是在运行时替换属性。
You can provide your own monitoring function (commonly called a spy), although this is not the most elegant. That would look like:
您可以提供自己的监控功能(通常称为间谍),尽管这不是最优雅的。那看起来像:
var called = false;
var testee = new ViewUnderTest();
var originalAttach = testee.attachSelect; // cache a reference to the original
testee.attachSelect = function () {
called = true;
var args = [].concat(arguments); // get an array of arguments
return originalAttach.apply(testee, args);
};
// Perform your test
expect(called).to.be.true;
If you have a test assertion library like chai, you can use the spies pluginand reduce that to:
如果你有一个像chai这样的测试断言库,你可以使用spies 插件并将其简化为:
var testee = new ViewUnderTest();
var spy = chai.spy(testee.attachSelect);
testee.attachSelect = spy;
// Perform your test
expect(spy).to.have.been.called();
Using a spy library will provide some useful features, such as monitoring the number of calls and their arguments to verify low-level behavior. If you're using Chai or Jasmine, I would highly suggest taking advantage of the corresponding support for spies.
使用 spy 库将提供一些有用的功能,例如监视调用次数及其参数以验证低级行为。如果您使用的是 Chai 或 Jasmine,我强烈建议您利用对 spies 的相应支持。