I'm using react testing library and redux.
I have a component having a button to dispatch redux action to get post then display on the screen.
const { posts, name } = useSelector((state) => state.posts)
const dispatch = useDispatch()
const handleClick = useCallback(() => {
dispatch(fetchPosts())
}, [])
return (
<div className="App" data-test="appComponent">
<button onClick={handleClick}>get post</button>
<section className="main">
<div>project name: {name}</div>
<Main posts={posts} />
</section>
</div>
)
on the testing file, what I want to test is that there is no text when page init load, after I click the button trigger the redux dispatch action, the screen should have text then.
describe("App test", () => {
const useSelectorMock = jest.spyOn(reactRedux, "useSelector")
const useDispatchMock = jest.spyOn(reactRedux, "useDispatch")
beforeEach(() => {
useSelectorMock.mockClear()
useDispatchMock.mockClear()
})
afterEach(() => {
jest.resetAllMocks()
clearnup()
})
it("test redux render", () => {
useSelectorMock.mockReturnValue({
posts: [],
})
const dummyDispatch = jest.fn()
useDispatchMock.mockReturnValue(dummyDispatch)
render(<App />)
const post = screen.queryByText("abc")
const button = screen.getByRole("button", {
name: "get post",
})
expect(post).toBeNull()
userEvent.click(button)
/* This is what I have tried.
useSelectorMock.mockReturnValue({
posts: [
{
title: "and I am thing2!",
body: "abc",
},
],
})
*/
const post2 = screen.getByText("abc")
expect(post2).toBeInTheDocument()
})
I have the init mock selector value, so the test of post is null is pass. However, when I trigger userEvent.click, it is not like the basic userEvent click to call a function then change the render. So the post2 is not working. I tried to change the useSelectorMock.mockReturnValue after button click trigger and want the selector value changes to the new one and render on screen too. But it's not working. I can only test the original selector value, but cannot test the updated new one.
How can I test the dispatch with react testing library?