I've been working on a typeScript program that interacts with an external API. While writing tests for this program, I've encountered challenges in properly mocking the dependency on the external API to analyze the values passed to the API itself.
A simplified snippet of my code that accesses the API looks like this:
const api = require("api-name")();
export class DataManager {
setup_api = async () => {
const email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d2dad6dedbf7c0d2d5c4dec3d299d2cfc3">[email protected]</a>";
const password = "password";
try {
return api.login(email, password);
} catch (err) {
throw new Error("Failure to log in: " + err);
}
};
Here is how I've set up my test logic:
jest.mock("api-name", () => () => {
return {
login: jest.fn().mockImplementation(() => {
return "200 - OK. Log in successful.";
}),
};
});
import { DataManager } from "../../core/dataManager";
const api = require("api-name"")();
describe("DataManager.setup_api", () => {
it("should login to API with correct parameters", async () => {
//Arrange
let manager: DataManager = new DataManager();
//Act
const result = await manager.setup_api();
//Assert
expect(result).toEqual("200 - OK. Log in successful.");
expect(api.login).toHaveBeenCalledTimes(1);
});
});
The issue I'm facing lies in the failing assertion
expect(api.login).toHaveBeenCalledTimes(1)
. This indicates that the API is indeed being mocked, but I am unable to access the original mock function. I suspect this might be due to replacing login
with a NEW jest.fn()
when called at the beginning of my test logic. I'm unsure how to prevent this or gain access to the mock function as I'm primarily concerned with verifying the function is called with the correct values rather than specific return results.
The challenge in mocking this library seems related to the way it's imported using
const api = require("api-name")();
, where parentheses are necessary after the require statement. However, I'm uncertain about its implications and impact on testing.