Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
React testing library how to test button click dispatch action

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda