【问题标题】:Reactjs test sinon spy mocked function returns a function and not a booleanReactjs 测试 sinon spy 模拟函数返回一个函数而不是布尔值
【发布时间】:2019-05-07 17:06:33
【问题描述】:

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

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

为此,我使用了 sinon spy 功能:

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 酶方法显然没有在这里返回布尔值。

我是 Reactjs 单元测试的新手,我有点迷茫。 .to.have.been.calledOnce 的返回值如何与 boolean 不同?

提前感谢您的帮助

【问题讨论】:

    标签: reactjs unit-testing enzyme sinon


    【解决方案1】:

    我还找到了另一种方法:

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

    【讨论】:

      【解决方案2】:

      看起来像 calledOnce is a sinon spy property,而不是 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);
      
      })
      

      【讨论】:

        猜你喜欢
        • 2017-02-04
        • 1970-01-01
        • 2014-03-14
        • 2021-10-22
        • 2021-12-11
        • 1970-01-01
        • 2020-04-23
        • 2017-07-23
        • 2015-10-05
        相关资源
        最近更新 更多