Within my .ts
module, I have the following code:
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 attempting to create a unit test for this class using ts-jest
in order to mock the behavior of client
and ensure it returns a valid Response
.
This is how I am proceeding:
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());
});
});
However, the mockedClient remains unmocked. Here is the content of ./client.ts
:
import { RestClient } from '@rest/client';
export default new RestClient();
Is there a way to successfully mock the internal client
module used by the DefaultRequest
class in this scenario?
EDIT:
I also attempted using 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);
Unfortunately, the original method is still being called instead of the spied method.