[英]Stubbing and/or spying on an optional global function: Sinon, mocha & chai
我有一個方法可以檢查是否定義了全局函數(它可能可用也可能不可用,取決於每個客戶的請求)。 如果已定義,它將使用適當的數據調用它。 如果沒有,它將靜默失敗。 這就是期望的行為。
我想做的是測試它。 有沒有辦法模擬和/或監視libFunction
以便我可以確保使用正確的數據調用一次它(這里的函數非常簡化,沿途會發生一些數據處理)。
這是有問題的方法:
function sendData(data) {
let exists;
try {
// eslint-disable-next-line no-undef
if (libFunction) exists = true;
} catch (e) {
exists = false;
}
if (exists) {
// eslint-disable-next-line no-undef
libFunction(data);
}
}
我已經嘗試在我的測試中定義libFunction
然后對其進行存根,但這並沒有達到我想要的效果:
describe('sendEvent', function () {
function libFunction(data) {
console.log('hi', data);
}
it('should call libFunction once', function () {
var stub = sinon.stub(libFunction);
var data = "testing";
sendEvent(data);
expect(stub.called).to.be.true;
});
});
但是,此測試未通過: AssertionError: expected undefined to be true
我用間諜嘗試過類似的事情:
describe('sendEvent', function () {
function libFunction(data) {
console.log('hi', data);
}
it('should call libFunction once', function () {
var spy = sinon.spy(libFunction);
var data = "testing";
sendEvent(data);
expect(spy.called).to.be.true;
});
});
這也失敗了: AssertionError: expected false to be true
有沒有辦法做到這一點?
FWIW,我在嘗試解決在 Node.js 中存根全局方法的問題時遇到了這個問題。 就我而言,這是有效的(我的示例使用Sinon.sandbox
,但“常規” Sinon.spy
應該有效):
const encodeSpy = sandbox.spy(global, "encodeURIComponent");
// later...
Sinon.assert.calledWith(encodeSpy, {expectedParamValue});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.