I'm currently utilizing typescript alongside jest for unit testing. My goal is to create a simple unit test, but it consistently fails no matter what I try. Below is the snippet of code in question:
// initialize.ts
let initialized = false;
let secretName: string;
export function init(name: string) {
if (initialized) {
throw new Error("Cannot re-initialize.");
}
secretName = name;
initialized = true;
}
export function getSecret(): string {
return secretName;
}
// initialize.test.ts
describe("init", () => {
async function getTestSubject() {
return await import("./initialize");
}
it("should properly set the secret name", async () => {
const init = await getTestSubject();
init.init("bruce wayne");
expect(init.getSecret()).toEqual("bruce wayne");
});
it("should trigger an exception if initialized more than once", async () => {
const init = await getTestSubject();
const callInit = function() {
init.init("bruce wayne");
};
callInit();
expect(callInit).toThrowError("Cannot re-initialize.");
});
});
The reason the second unit test fails is due to an exception being thrown. The first "callInit()" should be the initial invocation of 'init' within that specific unit test. However, due to the setup, it is considered as the second call when both tests are taken into account.
I initially attempted importing 'init' at the top globally like this:
import {init, getSecret} from "./init";
Do you have any suggestions on how to rectify this issue? I believe this is quite a fundamental test scenario, so either there's a major limitation with jest or I might be overlooking something obvious...
Appreciate your help!