use*_*826 2 reactjs moxios react-testing-library
我正在尝试使用钩子测试反应功能组件。useEffect 钩子调用第三方 API,然后在返回时调用 setState。
我有测试工作,但不断收到警告,指出组件的更新未包含在行为中。
我遇到的问题是期望在 moxios.wait 承诺内,因此我无法将其包装在行为函数中,然后对其结果进行断言。
测试通过了,但我知道不包装在行为函数中更新状态的代码可能会导致误报或未发现的错误。我只是想知道我应该如何测试这个。
我已经尝试在 react 16.9.0 alpha 版本中使用新的 async await 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)
})
}, [])
}
Run Code Online (Sandbox Code Playgroud)
考试
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()
})
})
})
})
Run Code Online (Sandbox Code Playgroud)
测试通过,但我收到以下警告
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)
Run Code Online (Sandbox Code Playgroud)
小智 5
从反应 16.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)
})
Run Code Online (Sandbox Code Playgroud)
我使用jest.fninmoxios.wait因为它需要回调函数
| 归档时间: |
|
| 查看次数: |
1095 次 |
| 最近记录: |