[英]Jest Act warning with useEffect
我已經使用 react-testing-library 設置了 Jest,並且我有一個這樣編寫的測試:
describe("Some Functionality", () => {
it("Should add a given product to the cart state", async () => {
const state = getMockState();
const { result: { getByTestId }, store } = deepRender(
<ProductView />,
{ initialState: state });
act(() => {
fireEvent.click(getByTestId("add-to-cart-btn"));
})
const newState = store.getState() as RootState;
expect(someassertion);
});
});
我的測試運行並通過,但我繼續收到一個警告,即 state 的更新未包含在 function 中。
我假設由於組件在加載時觸發了 useEffect ,它正在改變 state ,因此渲染方法也需要包裝在一個動作塊中,但這樣做:
act(() => {
const { result: { getByTestId }, store } = deepRender(
<ProductView />,
{ initialState: state });
fireEvent.click(getByTestId("add-to-cart-btn"));
})
不會消除警告,並且還會使結果中的存儲對 act 塊之外的斷言不可用。 有沒有辦法格式化它以減輕 act() 警告?
針對以下問題,組件的 useEffect 為:
useEffect(() => {
if (something) {
getDetails(something)
.then(getVariances)
.then(setProductVariances);
}
}, []);
這使用 useState 設置 productVariances state 值
您不需要將render
包裝在act
塊中。 您會收到行為警告,因為在解決 promise 之后存在 state 更新,因此 state 更新發生在行為塊之外。 我通常通過在我的測試中觸發await
更新的同一個 promise 來解決這個問題。
此外,您也不需要將fireEvent
包裝在 act 塊中,因為它在內部使用 act。
您需要等待任何改變 state 的副作用來解決,在這種情況下,我的方法是為組件提供處理此異步請求並在我的測試中模擬的服務的道具,然后在模擬服務上“等待”以解決.
這是一個例子:
it('renders when empty list of smartfields is passed', async () => {
const rendered = render(
<SomeComponent
someprop={'321'}
someotherprop={'123'}
serviceProp={yourServiceMocked}
/>
);
// here you would make assertions on your "loading" state
// HERE you await for you promise to resolve
await act(() => yourServiceMocked);
// here you would make assertions when your state has solved the promise
});
希望我過於簡化的示例有所幫助,我很難找到解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.