在行为回调中包装异步 moxios 调用 [英] Wrapping async moxios call in act callback
问题描述
我正在尝试使用钩子测试反应功能组件.useEffect 钩子调用第三方 API,然后在返回时调用 setState.
I am trying to test a react functional component using hooks. The useEffect hook makes a call to a third part API which then calls setState on return.
我进行了测试,但不断收到警告,指出组件的更新未包含在行为中.
I have the test working but keep getting a warning that an update to the component was not wrapped in act.
我遇到的问题是期望在 moxios.wait 承诺中,因此我无法将其包装在行为函数中,然后对其结果进行断言.
The problem I have is that the expectation is inside a moxios.wait promise and therefore I cannot wrap that in an act function and then assert on the result of that.
测试通过了,但我知道如果不包装在行为函数中更新状态的代码可能会导致误报或未发现的错误.我只是想知道我应该如何测试这个.
The test passes but I know not wrapping code that updates state in an act function could lead to false positives or uncovered bugs. I'm just wondering how I should be testing this.
我尝试在 react 16.9.0 alpha 版本中使用新的 async await act 函数,以及我在许多 github 问题(如 jest setTimers)中发现的许多建议,但似乎没有一个能解决问题.
I've tried using the new async await act function in the react 16.9.0 alpha release as well as numerous suggestions I've found in many github issues like jest setTimers and none seem to solve the issue.
组件
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)
})
}, [])
}
测试
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()
})
})
})
})
测试通过,但我收到以下警告
The test passes but I get the following warning
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 react16.9.0 你可以使用 async/await
act
from react 16.9.0 you can use 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)
})
我在 moxios.wait
中使用 jest.fn
因为它需要回调函数
I use jest.fn
in moxios.wait
because it needs callback function
这篇关于在行为回调中包装异步 moxios 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!