Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda