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

178
Views
Mocked class method only returns undefined

I'm testing a React class component which relies on a service for retrieving the user auth.

  async populateState() {
    const result = await authService.getUserAuthenticationStatus();
    const { user, isAuthenticated } = result;
    this.setState({
      isAuthenticated,
      user
    });
  }

So, I would like to mock the return value for getUserAuthenticationStatus like so:

jest.mock('./components/api-authorization/AuthorizeService');

beforeAll(() => {
  jest.spyOn(AuthService, 'getUserAuthenticationStatus').mockReturnValue(
    Promise.resolve({
      isAuthenticated: true,
      user: {}
    })
  );
});

The problem here, is that when running my tests, the method keeps returning undefined rather than the mock value I had set up in my test. If we take a quick look at the exported member, we can see the class is being instantiated and then exported. Could this be the issue?

const authService = new AuthorizeService();
export default authService;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think jest.mock is unnecessary here. You can simply spyOn the method since you already have an instance.

beforeAll(() => {
  jest.spyOn(authService, 'getUserAuthenticationStatus')
    // Returns promise no need to add manually
    .mockResolvedValue({ isAuthenticated: true, user: {} });
});

// And make sure you clear the mocks in the end. 
afterAll(() => jest.clearAllMocks());

Note: you are spying on the authService, not the AuthService

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!