我正在尝试使用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: Attempted to wrap undefined property marketLabel as function
发布于 2016-11-21 18:47:32
Sinon不能窥探不是某个对象属性的函数,因为Sinon必须能够将原始函数getMarketLabel替换为该函数的间谍版本。
下面是一个工作示例:
let obj = {
getMarketLabel(label) {
...
}
}
sinon.spy(obj, 'getMarketLabel');
// This would call the spy:
obj.getMarketLabel(...);此语法(与您正在使用的语法很接近)也存在:
let spy = sinon.spy(getMarketLabel);然而,这只在显式调用spy()时触发间谍代码;当您直接调用getMarketLabel()时,间谍代码根本不会被调用。
此外,这也不会起作用:
let getMarketLabel = (...) => { ... }
let obj = { getMarketLabel }
sinon.spy(obj, 'getMarketLabel');
getMarketLabel(...);因为您仍然直接调用getMarketLabel。
发布于 2016-11-21 19:09:02
这是我收到的错误:
TypeError: Attempted to wrap undefined property marketLabel as function
您需要将helper.js放入测试文件中,然后替换所需模块上的相关方法,最后调用替换为间谍的方法:
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')调用了间谍,因为此函数将在执行测试之前执行。因此,您可以这样写:
expect(spy).to.be.calledWith(helpers.sel('marketLabel'));
测试是否使用helpers.sel('marketLabel') (默认情况下为undefined )返回的任何值调用间谍。
helper.js的内容应该是:
module.exports = {
getMarketLabel: function (marketLabel) {
return marketLabel
}
}https://stackoverflow.com/questions/40717736
复制相似问题