Reactjs 测试 sinon 间谍模拟函数 returns 函数而不是布尔值

Reactjs test sinon spy mocked function returns a function and not a boolean

我正在尝试检查我的 InformationGatheringFormContainer 组件中的 formIsValid 方法是否在执行时调用组件道具之一 (isInfoFormValid):

export class InformationGatheringFormContainer extends React.Component{
...
formIsValid() {
    this.props.isInfoFormValid(this.state.invalid);
}

为此,我使用了 sinon 间谍功能:

it('formIsValid changes the state', () => {
    const mockFunction = sinon.spy();

    const baseProps = {
        isInfoFormValid: mockFunction,
    }

    const wrapper = shallow(<InformationGatheringFormContainer {...baseProps} />);
    wrapper.instance().formIsValid();
    expect(mockFunction).to.have.been.calledOnce.equal(true);

})

我希望它能工作,但是这个测试给出了:

AssertionError: expect(received).to.equal(expected)

Expected value to equal:
  true
Received:
  [Function proxy]

Difference:

  Comparing two different types of values. Expected boolean but received function.

因此确实检测到函数调用,但 .to.have.been.calledOnce 酶方法显然不是 return 布尔值。

我是 Reactjs 单元测试的新手,我有点迷茫。 .to.have.been.calledOnce 的 return 怎么可能有不同于 boolean 的类型?

提前感谢您的帮助

看起来像 calledOnce is a sinon spy property, not jest's expect。 所以,像这样:

expect(mockFunction.calledOnce).toEqual(true);

应该可以(如果你喜欢 sinon)。

值得注意的是jest has his own mocking mechanism:

it('formIsValid changes the state', () => {
    const isInfoFormValid = jest.fn();

    const baseProps = {
        isInfoFormValid,
    }

    const wrapper = shallow(<InformationGatheringFormContainer {...baseProps} />);
    wrapper.instance().formIsValid();
    expect(isInfoFormValid).toHaveBeenCalledTimes(1);

})

我还找到了另一种方法:

expect(mockFunction.callCount).toEqual(1);