如何用"Mocha"、"Chai"、"Sinon"检查一个功



如何使用MochaChaiSinon创建测试,以检查一个函数是否触发另一个函数。我想检查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调用对象Test内部的方法,该方法已被包裹funcToSpy的spy所取代。

在"使用函数"的情况下,funcToTrigger直接调用spy,而spy正在包装funcToSpy

在"使用函数参数"的情况下,funcToTrigger调用第一个参数,该参数是一个间谍,正在包装funcToSpy

相关内容

  • 没有找到相关文章

最新更新