【发布时间】:2021-04-02 00:17:16
【问题描述】:
我使用 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 块之外的断言不可用。有什么方法可以格式化它以减轻 act() 警告?
针对下面的一个问题,组件的useEffect是:
useEffect(() => {
if (something) {
getDetails(something)
.then(getVariances)
.then(setProductVariances);
}
}, []);
这使用 useState 设置 productVariances 状态值
【问题讨论】:
-
fireEvent内部使用行为? -
useEffect 是做什么的?给minimal reproducible example。
-
@jonrsharpe 在上面添加了一些细节
-
@evolutionxbox 那么这是否意味着将
fireEvent包装在一个动作块中是多余的? -
那么
getDetails是什么?您是否将其替换为测试替身进行测试?再次,给minimal reproducible example。我怀疑一种解决方案是延迟模式,因此您可以控制何时(以及是否)解决或拒绝,正如我在例如github.com/textbook/starter-kit/blob/…
标签: javascript reactjs jestjs react-testing-library