While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario:
// Library.ts
// Simulating a third party library
export class Library {
static code: number = -1;
}
// Consumer.ts
// Utilizing the Library in a basic manner
import { Library } from "./Library";
export function setCode(newCode: number) {
Library.code = newCode;
}
// Consumer.test.ts
// Testing the Consumer module
import { Library } from "./Library";
jest.mock("./Library", () => {
class Library {
static code: number = -11;
}
return { Library };
});
describe("Consumer", () => {
let consumer: typeof import("./Consumer");
beforeEach(() => {
jest.resetModules();
consumer = require("./Consumer");
});
it("should set code properly", () => {
consumer.setCode(3);
expect(Library.code).toEqual(3);
});
});
After setting the code to 3 in the test, I expected the mocked Library to be used and for Library.code to also be 3. However, it actually remains at -11 as defined in the mock factory. There seems to be something missing here, but I'm uncertain what it is.