Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!