Javascript 已调用Sinon Spy to check函数
我正在尝试使用Javascript 已调用Sinon Spy to check函数,javascript,testing,mocha.js,sinon,Javascript,Testing,Mocha.js,Sinon,我正在尝试使用sinon.spy()检查函数是否已被调用。该函数被称为getMarketLabel,它返回marketLabel,并将其接受到函数中。我需要检查是否调用了getMarketLabel。我实际上在一个地方调用了getMarketLabel,如下所示: {getMarketLabel(sel.get('market'))} 到目前为止,我掌握的代码是: describe('Check if it has been called', () => { let spy; be
sinon.spy()
检查函数是否已被调用。该函数被称为getMarketLabel
,它返回marketLabel
,并将其接受到函数中。我需要检查是否调用了getMarketLabel
。我实际上在一个地方调用了getMarketLabel
,如下所示:
{getMarketLabel(sel.get('market'))}
到目前为止,我掌握的代码是:
describe('Check if it has been called', () => {
let spy;
beforeEach(() => {
spy = sinon.spy(getMarketLabel, 'marketLabel');
})
it('should have been called', () => {
expect(spy).to.be.calledWith('marketLabel');
});
});
这是我收到的错误:
TypeError:试图将未定义的属性marketLabel包装为函数
Sinon无法监视不是某个对象属性的函数,因为Sinon必须能够用该函数的监视版本替换原始函数getMarketLabel
一个有效的例子:
let obj = {
getMarketLabel(label) {
...
}
}
sinon.spy(obj, 'getMarketLabel');
// This would call the spy:
obj.getMarketLabel(...);
此语法(与您使用的语法相近)也存在:
let spy = sinon.spy(getMarketLabel);
但是,这仅在显式调用spy()
时触发spy代码;直接调用getMarketLabel()
时,根本不会调用间谍代码
此外,这也不起作用:
let getMarketLabel = (...) => { ... }
let obj = { getMarketLabel }
sinon.spy(obj, 'getMarketLabel');
getMarketLabel(...);
因为您仍在直接调用getMarketLabel
这是我收到的错误:TypeError:试图包装未定义的内容
作为功能的属性标签
您需要在测试文件中输入helper.js,然后替换所需模块上的相关方法,最后调用替换为spy的方法:
var myModule = require('helpers'); // make sure to specify the right path to the file
describe('HistorySelection component', () => {
let spy;
beforeEach(() => {
spy = sinon.stub(myModule, 'getMarketLabel'); // replaces method on myModule with spy
})
it('blah', () => {
myModule.getMarketLabel('input');
expect(spy).to.be.calledWith('input');
});
});
您无法测试是否使用helpers.sel('marketLabel')
调用spy,因为此函数将在执行测试之前执行。因此,您将通过书面形式:
expect(spy).to.be.calledWith(helpers.sel('marketLabel')代码>
测试spy是否使用helpers.sel('marketLabel')
返回的任何值调用(默认情况下,未定义)
helper.js的内容应该是:
module.exports = {
getMarketLabel: function (marketLabel) {
return marketLabel
}
}
但我不确定助手文件中应该包含什么。目前这是我的问题:我仍然收到相同的错误。@DaveDavidson:请参阅更新的答案。不确定为什么执行无效语法的返回{getMarketLabel}
。我将其更改为退货市场标签
。这对我不起作用。我仍然会遇到同样的错误。@DaveDavidson:请参阅更新的答案。您正在尝试存根该方法。因此,您需要使用sinon.stub()。@rabbitco{getMarketLabel}
是有效的ES6语法,它是{getMarketLabel:getMarketLabel}
@DaveDavidsonsinon.spy(getMarketLabel,'marketLabel')
的缩写:getMarketLabel
不是对象,marketLabel
不是函数。