Javascript 戏谑行为警告,有效

Javascript 戏谑行为警告,有效,javascript,reactjs,jestjs,react-testing-library,Javascript,Reactjs,Jestjs,React Testing Library,我已经使用react测试库设置了Jest,并编写了一个测试: describe("Some Functionality", () => { it("Should add a given product to the cart state", async () => { const state = getMockState(); const { result: { getByTestId }, store } = dee

我已经使用react测试库设置了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);
});
});

这将使用useState设置productVariances状态值,而无需将
呈现
包装到
动作
块中。您将收到act警告,因为在承诺解析后有状态更新,因此状态更新发生在act块之外。我通常通过
等待
来解决这个问题,因为它的解决方案是在我的测试中触发状态更新


此外,您也不需要在act块中包装
fireEvent
,因为它在内部使用act。

fireEvent
在内部使用act?useEffect在做什么?给出一个例子。@jornsharpe添加了一些细节above@evolutionxbox那么,这是否意味着将
fireEvent
包装到act块中是多余的?以及
getDetails
是什么?您是否将其替换为用于测试的双重测试?再一次,给我一个建议。我怀疑一种解决方案是延迟模式,因此您可以控制何时(以及是否)解决或拒绝,如我在示例Interesting中所示。我想测试:`useffect(()=>{storage.readObject('has_accepted_cookie')。然后((value)=>setVisible(!value))},[])`,我怎么能在这里等待呢?这对我来说似乎是不可能的。您必须模拟任何storage.readObject,以便在测试中获得对其返回值的引用
    act(() => {
        const { result: { getByTestId }, store } = deepRender(
             <ProductView />,
             { initialState: state });

        fireEvent.click(getByTestId("add-to-cart-btn"));
    })
useEffect(() => {
    if (something) {
        getDetails(something)
        .then(getVariances)
        .then(setProductVariances);
    }
}, []);