我正在重构一个TypeScript方法,以添加一个带有默认值的可选参数。重构方法是一个核心操作,有许多高级操作调用核心函数。预先存在的调用忽略新参数(因此使用默认值),而新建和重构方法则提供新的参数值。简化的版本如下所示:
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);
}
}我也在更新高级操作的茉莉花测试。我想断言,高级别操作会导致使用某些参数调用核心操作。测试大致如下所示:
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);
});
});
});问题是茉莉花的toHaveBeenCalledWith不知道第二个参数有一个默认值。上述代码的错误:
- Expected spy coreOperation to have been called with:
[ 'main1', false ]
but actual calls were:
[ 'main1' ],
[ 'main2', true ].显然,我可以通过从测试中移除false参数来通过测试。但是,我不想让测试知道调用站点是使用1参数还是使用2,特别是来自像本例这样的私有库函数。
是否有一种方法可以在省略可选参数和传递默认值时使用Jasmine?
发布于 2022-05-28 00:55:01
不幸的是,没有办法窥探茉莉花中的默认/可选参数。
之所以不可能这样做,有几个原因:
在被调用方法的作用域中存在的
arguments数组变量中设置的,它们不是传递给的实际值,只能测试该方法用什么参数调用,而不是该方法决定将其缺失的参数默认给.的值。为了解决这个问题,您可以将目标方法包装在包含option: boolean = false默认参数的另一个方法中。然后,您应该能够检查使用什么方法调用coreOperation:
coreOperation(mainArg: string, option: boolean) {
// ...
}
private coreOperationDefaultWrapper(mainArg: string, option: boolean = false) {
this.coreOperationmainArg(mainArg, option);
}值得注意的是,最好的测试是测试应用程序的功能,而不是如何编写应用程序。因此,我强烈建议使用测试默认参数会导致什么行为的思维方式,而不是检查它们的实际情况。当然,这并不总是可能的,我希望上面的例子能够帮助您!:)
https://stackoverflow.com/questions/72412029
复制相似问题