测试库和 fireEvent 的问题

时间:2021-05-01 05:37:33

标签: javascript reactjs testing jestjs react-testing-library

我可以正确渲染我的组件并使用 .getByPlaceholderText 获取输入标签。问题是在我使用 fireEvent 更改输入值后,我无法使用 findByText 获得相同的输入。这不是我要使用的测试;我只是想了解为什么这不起作用。

    it('displays the clearIcon by default', async () => {
      // Render my component
      render(<SearchInput {...defaultProps} />)
      // find the input html element by placeholder - it works
      const inputNode = await screen.findByPlaceholderText(/search/i)
      // fire an event where I change the value of the input to "Text"
      fireEvent.change(inputNode, { target: { value: 'Text' } })
      // find the same element searching by the text I added in it - "Text"
      // this fails saying that it's "unable to find an element with the text /Text/i"
      const sameInput = await screen.findByText(/Text/i)
      expect(sameInput).toBeInTheDocument()
    })

1 个答案:

答案 0 :(得分:0)

问题是我试图测试嵌套组件,而输入值的状态在包装器组件中。将我的测试移至包装组件解决了这个问题。