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

412
Visualizações
How to mock useState using Jest?

I am using Jest and react-testing-library in React application. I have to test following scenario -

function Parent () {
    const [country, setCountry] = useState(true)

    return (
        <Child setCountry={setCountry} />
    )
}

function Child () {    
    const handleValueClear = () => {
        setCountry(false)
        const data = {
            id : 'IND',
            name : 'India'
        }
        dispatch(handleCountryDetails(data))
    }
    return (
        <div>
            <button onclick={handleValueClear}>Click me</button>
        </div>
    )
}

How to mock and test useState in jest ?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Your component

import React from 'react'

function Parent () {
    const [country, setCountry] = React.useState(true)

    return (
        <Child setCountry={setCountry} />
    )
}

function Child () {    
    const handleValueClear = () => {
        setCountry(false)
        const data = {
            id : 'IND',
            name : 'India'
        }
        dispatch(handleCountryDetails(data))
    }
    return (
        <div>
            <button onclick={handleValueClear}>Click me</button>
        </div>
    )
}

Jest file for Parent

test('useState mock', () => {
   const initialState = true

   React.useState = jest.fn().mockReturnValue([initialState , {}])
   
   const wrapper = shallow(<Parent />)

   // In this point your state set and you can test the rest
}
about 4 years ago · Santiago Gelvez Relatório
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