Jest 存储状态和 RTL 呈现组件的 onClick 事件处理程序不同的状态
Jest store state and RTL rendered component's onClick event handler different states
我正在使用以下代码使用 jest 和 rtl 测试依赖于状态的 React 组件:
test("render author, date and image correctly after going next post", async () => {
const store = configureStore({
reducer: {
data: dataReducer
}
});
const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
);
render(<Post />, { wrapper: Wrapper });
const getSpy = jest.spyOn(axios, 'get').mockReturnValue(mockPostJSON);
await store.dispatch(FETCH_POSTS());
expect(getSpy).toBeCalledWith('https://www.reddit.com/r/EarthPorn/.json');
const beforeClick = await screen.findByTestId('authorAndDate');
expect(beforeClick.innerHTML.toString()).toBe(mockPostsList[0].author + ' - ' + mockPostsList[0].date);
fireEvent.click(screen.getByText('Next post'));
const afterClick = await screen.findByTestId('authorAndDate');
expect(afterClick.innerHTML.toString()).toBe(mockPostsList[1].author + ' - ' + mockPostsList[1].date);
})
我遇到的问题是,在单击之前,商店中的所有内容都已正确设置,并且 authorAndDate 元素显示帖子数组中的第一项。但是在点击被触发后,商店会回到加载模拟数据之前的初始状态。我检查了组件的事件处理程序,就在它执行任何操作之前,状态已被重置。代码如下:
const handleNextClick = () => {
store.dispatch(GO_NEXT_POST());
store.dispatch(FETCH_COMMENTS());
}
我花了一个小时研究代码,试图找到可以重置状态的东西,但一无所获。我猜这是 jest 和 rtl 之间的某种交互,但我不明白为什么测试中的商店有一个状态而组件事件处理程序中的商店有另一个状态:S
好吧,想通了。不能直接使用 store.dispatch,因为它正在访问陈旧状态。需要使用 useDispatch 挂钩。希望这对以后遇到同样问题的任何人都有帮助。
我正在使用以下代码使用 jest 和 rtl 测试依赖于状态的 React 组件:
test("render author, date and image correctly after going next post", async () => {
const store = configureStore({
reducer: {
data: dataReducer
}
});
const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
);
render(<Post />, { wrapper: Wrapper });
const getSpy = jest.spyOn(axios, 'get').mockReturnValue(mockPostJSON);
await store.dispatch(FETCH_POSTS());
expect(getSpy).toBeCalledWith('https://www.reddit.com/r/EarthPorn/.json');
const beforeClick = await screen.findByTestId('authorAndDate');
expect(beforeClick.innerHTML.toString()).toBe(mockPostsList[0].author + ' - ' + mockPostsList[0].date);
fireEvent.click(screen.getByText('Next post'));
const afterClick = await screen.findByTestId('authorAndDate');
expect(afterClick.innerHTML.toString()).toBe(mockPostsList[1].author + ' - ' + mockPostsList[1].date);
})
我遇到的问题是,在单击之前,商店中的所有内容都已正确设置,并且 authorAndDate 元素显示帖子数组中的第一项。但是在点击被触发后,商店会回到加载模拟数据之前的初始状态。我检查了组件的事件处理程序,就在它执行任何操作之前,状态已被重置。代码如下:
const handleNextClick = () => {
store.dispatch(GO_NEXT_POST());
store.dispatch(FETCH_COMMENTS());
}
我花了一个小时研究代码,试图找到可以重置状态的东西,但一无所获。我猜这是 jest 和 rtl 之间的某种交互,但我不明白为什么测试中的商店有一个状态而组件事件处理程序中的商店有另一个状态:S
好吧,想通了。不能直接使用 store.dispatch,因为它正在访问陈旧状态。需要使用 useDispatch 挂钩。希望这对以后遇到同样问题的任何人都有帮助。