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

249
Views
How can mock class methods inside class be tested?

I have a mock class for a web service:

src/_mocks _/ExternalService.ts

export default class ExternalService {

  async queryService(skus: string): Promise<any> {
    try {
      return await this.mockResponse;
    } catch (error) {
      return error;
    }
  }

  mockResponse: any = {
    data: {
      recordSetCount: 6,
      isMock: true,
      items: [
       // Mock items
      ]
    }
  };

This method correctly calls the mock class in Jest:

src/Accesories.ts

  async getAccesoriesFromService(skus: string): Promise<any> {
    const externalService = new ExternalService();
    const productsData = [];
    
    try {
      const products = await externalService.queryService(skus);

      if (!products.data?.items?.length) {
        return { errorCode: -4 };
      }

      ... 

      return { errorCode: 0, products: productsData };
    } catch (error) {
      return { errorCode: -1, error };
    }
  }

In this test I want to override the mock with another mock:

_ tests__/main.spec.ts

const accesories = new Accesories();
const externalService = new ExternalService();

jest.mock('../src/ExternalService');

it('get no accesories from service', async () => {
  const mockResponseNoRecords: any = {
    data: {
      recordSetCount: 0,
      items: [] // empty array
    }
  };
  jest.spyOn(externalService, 'queryService').mockImplementation((): any => {
    return mockResponseNoRecords;
  });

  try {
    await accesories.getAccesoriesFromService('string with skus');
  } catch (error) {
    expect(error.errorCode).toBe(-4);
  }
}

But when I run the test, I get these results from console.log:

  console.log
    products in test code:  {
      mockResponseNoRecords: {
        data: {
        recordSetCount: 0,
        items: []
      }
    }

      at __tests__/main.spec.ts:96:11

  console.log
    products in actual code:  {
      data: {
        recordSetCount: 6,
        isMock: true,
        items: [
          // Items from the mock class
        ]
      }
    }

And the test passes because the original mock was called, it was not successfully spied

What I want to achieve is to override the method in the mock class in order to make it fail, but the original mock is being called.

about 4 years ago · Santiago Trujillo
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!