在 act 回调中包装异步 moxios 调用

2024-03-30

我正在尝试使用钩子测试反应功能组件。 useEffect 挂钩调用第三方 API,然后在返回时调用 setState。

我已经进行了测试,但不断收到警告,表明组件的更新未包含在 act 中。

我遇到的问题是期望位于 moxios.wait 承诺内,因此我无法将其包装在 act 函数中,然后对其结果进行断言。

测试通过了,但我知道不将更新状态的代码包装在 act 函数中可能会导致误报或未发现的错误。我只是想知道我应该如何测试这个。

我尝试过在 React 16.9.0 alpha 版本中使用新的 async wait act 函数,以及我在许多 github 问题(如 jest setTimers)中找到的大量建议,但似乎都没有解决问题。

组件

 const Benefits = props => {
  const [benefits, setBenefits] = useState([])
  const [editing, setEditing] = useState(false)
  const [editingBenefit, setEditingBenefit] = useState({id: null, name: '', category: ''})

  useEffect(() => {
    axios.get('#someurl')
      .then(response => {
        setBenefits(response.data)
    })
  }, [])
}

The test

describe('Benefits', () => {
  it('fetches the list of benefits from an api and populates the benefits table', (done) => {
    const { rerender } = render(<Benefits />)
    moxios.wait(() => {
      const request = moxios.requests.mostRecent()
      request.respondWith({
        status: 200,
        response: benefits
      }).then(() => {
        expect(document.querySelectorAll('tbody > tr').length).toBe(2)
        done()
      })
    })
  })
})

测试通过,但我收到以下警告

Warning: An update to Benefits inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser.
    in Benefits (at benefits.spec.js:28)

from 反应16.9.0 https://github.com/facebook/react/releases/tag/v16.9.0您可以使用async/await act

你的代码应该是这样的

describe('Benefits', () => {
  it('fetches the list of benefits from an api and populates the benefits table', async() => {
    const { rerender } = render(<Benefits />);

    await moxios.wait(jest.fn);
    await act(async() => {
      const request = moxios.requests.mostRecent()
      await request.respondWith({
        status: 200,
        response: benefits
      });
    });

    expect(document.querySelectorAll('tbody > tr').length).toBe(2)
})

I use jest.fn in moxios.wait因为需要回调函数

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 act 回调中包装异步 moxios 调用 的相关文章

随机推荐