我正在尝试使用 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()
时,根本不会调用 spy 代码。
另外,这也行不通:
let getMarketLabel = (...) => { ... }
let obj = { getMarketLabel }
sinon.spy(obj, 'getMarketLabel');
getMarketLabel(...);
因为您仍在直接调用 getMarketLabel
。
关于javascript - Sinon Spy 检查功能已被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40717736/