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

156
Visualizações
How to mock set state and method from protected abstracts method in React Jest

This is how the components are arranged

class A extends React.Component {
  state = {mode: 'create'}

  abstract getRows() {
    
  }

  abstract getTitle(){
     
  }
}

class B extends A {
   getTitle(){
     if(this.state.mode === 'create'){ return 'New';}
     else {return 'Existing'};
   }
}

And in test case:

jest.mock('componentAFile');

component = shallow(<B />);

component.setState({mode: 'create'});
expect(component.instance().getTitle()).toBe('New');

component.setState({mode: 'edit'});
expect(component.instance().getTitle()).toBe('Existing');

But state mode says undefined. What is the correct way to do this? How do we test such classes inheriting from base classes?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, better don't use that inheritance approach. Composition is so many way better that I even cannot recall any cons of inheritance.

Second, using .setState you are literally accessing internal aka private data. Or in other words "implementation details". There are so many cases when it breaks suddenly(renamed property in this.state, refactored class component into function, decompose one component into several etc etc), that there are no reason to use it.

Third, the same is with testing internal methods. Again, it's implementation details, for both name, arguments ordering, result returned. And moreover, let's assume you never use that function in what component renders in render(). So test will pass, but component might be broken.

What can you do instead?

  1. Provide prop(shallow(<B prop1={mockedValue} prop2={anotherValue} />);)
  2. change prop(.setProps)
  3. call callback(component.find('button').simulate('click'))
  4. validate against rendering results: expect(component.find('.title').text()).toBe('New')
  5. also we may want to validate whether some mocked external service/utility has been called(but your case probably does not need that; just want to have complete list)
about 4 years ago · Juan Pablo Isaza 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