I am currently revising a TypeScript function to include an optional parameter with a default value. This function is a crucial operation, and it is utilized by several high-level operations. Existing calls to the function do not include the new parameter (thus utilizing the default value), while new and revised methods provide a value for the new parameter. An example of the simplified version is as follows:
export class Scratch {
coreOperation(mainArg: string, option: boolean = false) {
// ...
}
private midLevelOperation(mainArg: string) {
this.coreOperation(mainArg + '1');
}
highLevelOperation1(mainArg: string) {
this.midLevelOperation(mainArg);
this.coreOperation(mainArg + '2', true);
}
}
I am also updating the Jasmine tests for the higher-level operations. I aim to confirm that these operations trigger the core operation with specific parameters. The tests would resemble the following:
describe('Scratch', () => {
let objectUnderTest: Scratch;
beforeEach(() => {
objectUnderTest = new Scratch();
spyOn(objectUnderTest, 'coreOperation');
});
describe('highLevelOperation1', () => {
it('should call core operation', () => {
objectUnderTest.highLevelOperation1('main');
expect(objectUnderTest.coreOperation).toHaveBeenCalledWith('main1', false);
expect(objectUnderTest.coreOperation).toHaveBeenCalledWith('main2', true);
});
});
});
The issue arises when using Jasmine's toHaveBeenCalledWith
because it does not recognize that the second argument has a default value. The error message for the provided code is as follows:
- Expected spy coreOperation to have been called with:
[ 'main1', false ]
but actual calls were:
[ 'main1' ],
[ 'main2', true ].
To resolve this, one could remove the false
argument from the test in order to pass. However, it is preferable for the tests not to be aware of whether call sites use one or two arguments, particularly in cases involving private library functions like the one shown here.
Is there a feasible approach to create a Jasmine matcher that functions effectively regardless of whether an optional parameter is excluded or if the default value is supplied?