I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I haven't been successful.
Below is a snippet of my code:
auth.controller.ts
import { AxiosService } from "helpers";
export class AuthController {
constructor() {
...
// Some logic here
this.init()
}
public init() {
// Setting up a route for login
router.post('/api/auth/login', this.login);
}
login = async function (req: Request, res: Response): Promise<void> {
// Configuring axios call with some logic
...
// Service for Axios call to a third party.
AxiosService.call(req, res, config, "login");
}
}
auth.test.ts
import { AuthController } from "../../modules/auth/auth.controller";
jest.mock("../../modules/auth/auth.controller");
beforeAll(async () => {
const auth = new AuthController();
mockLogin = jest.spyOn(auth, "login");
});
afterAll(async () => {
server.stop();
});
test("should give login response", async () => {
mockLogin.mockImplementation(() => {
return Promise.resolve({ Success: true, body: "Login" });
});
const response = await request(server.app)
.post("/api/auth/login")
.send(requestBody)
.expect(200);
response.body // Receiving actual server response instead of the mocked one
})
Also attempted the following code but encountered no luck:
jest.mock('../../modules/auth/auth.controller', () => {
return {
AuthController: jest.fn().mockImplementation(() => {
return {
login: jest.fn()
}
})
}
})
Here's how my AxiosService class looks:
export class AxiosService {
public static async call(...):Promise<void> {
try {
const { data } = await axios(...);
res.status(200).json(data);
} catch(err) {
res.status(400).send(err);
}
}
}
Tried to mock the AxiosService call method as shown below:
jest.mock('../../helpers/AxiosService', () => {
return jest.fn().mockImplementation(() => {
return { call: () => { return {success:true, data:'mock'}} }
})
})
However, even after mocking the Axios call, I keep receiving an error message stating "Async callback was not invoked within the 10000 ms timeout specified by jest.setTimeout".
If anyone can offer assistance, it would be greatly appreciated since I'm fairly new to the concept of mocking and may have overlooked something.
Thanks in advance