I am currently working on testing my TypeScript functions with Jasmine:
//AB.ts
export async function A() {
}
export async function B() {
A();
}
My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I have so far:
//AB.spec.ts
import * as AB from './AB'
describe('AB has a function B that ', () => {
it('calls A', async () => {
let ASpy: jasmine.Spy;
ASpy = spyOn(AB, 'A').and.returnValue(Promise.resolve({}));
await AB.B();
expect(ASpy).toHaveBeenCalled();
});
});
Upon running the test, I received an error indicating that ASpy was never called. However, after investigating further, I confirmed that the A function was indeed called. It seems like the mock I created for the function did not trigger as expected. I tried relocating the A function to a separate file and mocked it there for the test in AB.spec.ts; surprisingly, the test passed as the expectation showed that ASpy was called. I'm puzzled as to why having both functions in the same file caused the test to fail while separating them into different files made it pass. I would appreciate any insights or help on this matter! Although moving the functions to separate files solved the issue for now, I prefer not to rely on this approach in future projects.