首页 > 解决方案 > 如何使用`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;
});

标签: javascriptunit-testingmocha.jschaisinon

解决方案


基于文档

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


推荐阅读