I have a following .ts module
import client from './client'; export default class DefaultRequest implements IRequest { make(req: Request): Promise<Response> { return new Promise<Response>((resolve, reject) => { client.post(req, (error: Error | null, res: Response) => { if (error) { return reject(error); } else { return resolve(res); } }); }); } } I am trying to write a unit test for this class with ts-jest, so that client is mocked (and returns some valid Response).
Here is how I am doing it:
import {mocked} from 'ts-jest/utils'; import client from './client'; import DefaultRequest from './request' const mockedClient = mocked(client, true); const testRequest = new DefaultRequest(); jest.mock('./client', () => { return { RestClient: jest.fn().mockImplementation(() => { return { post: () => {return someValidResponse();}, }; }) }; }); describe('My Tests', () => { it('Unit Test 1', async () => { let res: Response = await testRequest.make(buildReq()); }); }); But the mockedClient is still not mocked. This is what ./client.ts looks like:
import { RestClient } from '@rest/client'; export default new RestClient(); Can the internal client module that class DefaultRequest uses be mocked in this manner?
EDIT: I also tried jest.spyOn
const spiedMethod= jest.spyOn(client, 'post'); const call: Request = new Request(); const response: Response = await call.make(buildRequest()); expect(spiedReleaseMethod).toHaveBeenCalled(); expect(response.getResponsecode()).toBe(200); And it still calls the original method and not the spied method.