javascript - 如何使用`Mocha`,`Chai`,`Sinon`检查一个函数是否触发另一个函数
问题描述
如何使用Mocha
, Chai
,创建测试Sinon
以检查一个函数是否触发另一个函数。我想检查是否funcToTrigger
触发funcToSpy
import { expect } from 'chai';
import sinon from 'sinon';
it('one function should trigger other function', () => {
const funcToSpy = () => {
console.log('I should be called');
};
const funcToTrigger = () => {
funcToSpy();
};
const spyFunc = sinon.spy(funcToSpy);
funcToTrigger();
expect(spyFunc.called).to.be.true;
});
当我只测试一个功能时,它工作正常:
it('function should be called', () => {
const funcToSpy = () => {
console.log('I should be called');
};
const spyFunc = sinon.spy(funcToSpy);
spyFunc();
expect(spyFunc.called).to.be.true;
});
解决方案
基于文档:
var spy = sinon.spy(myFunc);
将函数包装在一个间谍中。当您需要验证函数的使用方式时,您可以将这个间谍传递给原始函数,否则将传递该函数。
使用示例:
import { expect } from 'chai';
import sinon from 'sinon';
it('use Object', () => {
const Test = {
funcToSpy: () => {
console.log('I should be called');
},
};
const funcToTrigger = () => {
Test.funcToSpy();
};
const spyFunc = sinon.spy(Test, 'funcToSpy');
funcToTrigger();
expect(spyFunc.called).to.be.true;
});
it('use Function', () => {
const funcToSpy = () => {
console.log('I should be called');
};
const spyFunc = sinon.spy(funcToSpy);
const funcToTrigger = () => {
spyFunc();
};
funcToTrigger();
expect(spyFunc.called).to.be.true;
});
it('use Function Argument', () => {
const funcToSpy = () => {
console.log('I should be called');
};
const funcToTrigger = (funcToSpy) => {
funcToSpy();
};
const spyFunc = sinon.spy(funcToSpy);
funcToTrigger(spyFunc);
expect(spyFunc.called).to.be.true;
});
结果:
$ npx mocha index.spec.js
I should be called
✓ use Object
I should be called
✓ use Function
I should be called
✓ use Function Argument
3 passing (3ms)
$
您的测试失败,因为:funcToTrigger
已定义并始终调用原始funcToSpy
.
在“使用对象”的情况下,funcToTrigger
调用 object 内部的方法Test
,该方法已被 spy 替换,即 wrapping funcToSpy
。
在 'use Function' 的情况下,funcToTrigger
直接调用 spy,spy 是 wrapping 的funcToSpy
。
在“使用函数参数”的情况下,funcToTrigger
调用第一个参数,它是一个间谍,它是 wrapping funcToSpy
。
推荐阅读
- angular - FileReader 属性的 jasmine spyon readAsBinaryString 方法
- firebase - 当我订阅一个不存在的主题时,Firebase 会创建一个主题吗?
- c - C中的冒泡排序
- c# - 如何在 wpf 中关闭和重新打开一个窗口?
- javascript - 如何停止执行 foreach 直到它内部的 API 调用结束?
- python - Python:如何使用 PyPDF2 解密和 pdfminer 提取文本?
- python - 在使用 microsoft graph api 的某些情况下,电子邮件是无(在获取用户数据时)
- typescript - 只有两个可能值的属性字符串
- javascript - fluent-ffmpeg 没办法加速 GIF
- xpath - Google 表格中的 ImportXML 函数会产生错误“导入的内容为空”!