In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file:
export function test1(param1, param2, param3, param4) {
return { param1, param2, ...(param3 && { param3 }), ...(param4 && { param4 }) };
}
export function test2(param1, param2) {
return test1(param1, null, null, param2);
}
For the test case, I want to confirm that the first function is being called by the second function:
import * as Util from './my-util-file';
const test2 = Util.test2;
...
it('should call test1 when test2 is called', () => {
const test1 = spyOn(Util, 'test1').and.callThrough();
test2('test', 1);
expect(test1).toHaveBeenCalledWith('test', null, null, 1);
});
Alternatively,
import {test1, test2} from './my-util-file';
...
it('should call test1 when test2 is called', () => {
const test1Spy = jasmine.createSpy('test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
Or
import * as Util from './my-util-file';
const test2 = Util.test2;
...
it('should call test1 when test2 is called', () => {
const test1Spy = spyOnProperty(Util, 'test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
Or
import {test1, test2} from './my-util-file';
...
it('should call test1 when test2 is called', () => {
const test1Spy = spyOn(window as any, 'test1');
test2('test', 1);
expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});
However, I encountered the following error:
Expected spy test1 to have been called.