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.