I am currently trying to test my typescript functions using Jasmine:
//AB.ts
export async function A() {
}
export async function B() {
A();
}
I am trying to unit test the function B by mocking out A. I want to see if A is called. Here is what I have:
//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();
});
});
When I run this test, I am told that ASpy was never called. However upon further investigation, I found that the A function was definitely called. So it seems like the A function was called but the mock I created for the function was not triggered. I've tried implementing the A function in a different file and calling that in B and mocking that out in AB.spec.ts; in that scenario, the test passes as the expect determines that the ASpy was called. I'm not sure why having the two functions in the same file together breaks the test but putting them in separate files passes the tests. Anyway, I'm hope to hear from someone soon! I'm fine with putting the functions in separate files but I want to avoid it as much as possible in future projects.
I was able to find a way to properly mock out A inside of B. Just needed to add the exports keyword to my function call:
export async function B() {
exports.A();
}
This allows the scope of B to see the definition of A while also allowing the .spec file to see that A is reverencing the exported method of A.