我正在尝试使用钩子测试反应功能组件。 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)