我使用 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);
});
});
我的测试运行并通过,但我继续收到行为警告,指出状态更新未包含在行为函数中。
我假设由于组件在加载时触发了 useEffect,它改变了渲染方法需要包装在行为块中的状态,但这样做:
act(() => {
const { result: { getByTestId }, store } = deepRender(
<ProductView />,
{ initialState: state });
fireEvent.click(getByTestId("add-to-cart-btn"));
})
不会消除警告,并且还会使结果的存储对行为块外的断言不可用。有没有办法格式化它以减轻 act() 警告?
在回答下面的一个问题时,组件的 useEffect 是:
useEffect(() => {
if (something) {
getDetails(something)
.then(getVariances)
.then(setProductVariances);
}
}, []);
这使用 useState 设置 productVariances 状态值
答案 0 :(得分:1)
您不需要将 render
包装在 act
块中。您收到行为警告,因为在承诺解决之后有状态更新,因此状态更新发生在行为块之外。我通常通过await
在我的测试中触发状态更新的同一个承诺来解决这个问题。
此外,您也不需要将 fireEvent
包装在行为块中,因为它在内部使用了行为。