【问题标题】:Testing a function and not getting correct result for .toHaveBeenCalled() method测试一个函数但没有得到 .toHaveBeenCalled() 方法的正确结果
【发布时间】:2020-08-19 23:15:27
【问题描述】:

我正在测试以下功能:

onSubmit = e => {
        e.preventDefault()
        if (!this.state.measureURI) return
        this.setState({ foodId: this.props.food.foodId }, () => this.props.fetchServing({
            quantity: parseInt(this.state.quantity),
            measureURI: this.state.measureURI,
            foodId: this.state.foodId
        }))
    }

测试:

    test('should test onSubmit prop for valid form submission', () => {
        const onSubmit = jest.fn()
        const fetchServing = jest.fn()
        const arg = {
            quantity: expect.any(Number),
            measureURI: expect.any(String),
            foodId: expect.any(Number)
        }
        const wrapper = shallow(<ServingForm food={food} onSubmit={onSubmit} fetchServing={fetchServing} />)
        wrapper.find('form').simulate('submit', {
            preventDefault: () => { }
        })
        expect(fetchServing).toHaveBeenCalled()
    })

但是,我收到以下错误:

● <ServingForm /> › should test onSubmit prop for valid form submission
    expect(jest.fn()).toHaveBeenCalled()
    Expected number of calls: >= 1
    Received number of calls:    0
      37 |             preventDefault: () => { }
      38 |         })
    > 39 |         expect(fetchServing).toHaveBeenCalled()
         |                              ^
      40 |     })
      41 | 
      42 | })

我做错了什么?

我正在使用 jest 和酶对间谍进行单元测试。

【问题讨论】:

  • 在您的测试运行期间this.state.measureURI 是什么?
  • 它只是确保选择了实际测量
  • 您的测试是否确保在运行前选择测量?
  • 我不是,你能告诉我我会怎么做吗,确实是因为那条线,因为我评论了// if (!this.state.measureURI) return,然后重新运行测试,它可以工作,但我不确定如何确保在测试中选择测量值

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

您的测试代码永远不会到达fetchServing 调用,因为this.state.measureURI 没有值,所以它只是在那个时候返回。我对酶不熟悉,但根据docswrapper 具有setState 功能,因此您可以:

wrapper.setState({ measureURI: 'whatever' });

【讨论】:

  • 谢谢,我在调用提交之前模拟了一个更改度量 URI 的调用,它有效const value = "cup"; wrapper.find("select").simulate("change", { target: { value }, })
猜你喜欢
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
相关资源
最近更新 更多