spyOn 即使通过函数也不会被调用
spyOn is not called even though it passed through the function
我为 ngOnChanges
创建了一个测试,但即使它通过了函数,
有一个错误
Error: Expected spy selectItem to have been called.
这是我的 ngOnChange
ngOnChanges(changes: SimpleChanges): void {
const eventDataChange: SimpleChange = changes['selectEventData'];
if (eventDataChange) {
this.selectItem(eventDataChange.currentValue);
}
}
这是单元测试:
describe('ngOnChange()', () => {
it('this is a description', () => {
const selectDto = 'test';
const eventDataChange: SimpleChange = new SimpleChange(null, selectDto, false);
const simpleChanges: SimpleChanges = {
selectEventData: eventDataChange
};
component.ngOnChanges(simpleChanges);
const selectSpy = spyOn(component, 'selectItem');
expect(selectSpy).toHaveBeenCalled();
});
});
希望得到善意的回应!
谢谢!
spyOn
间谍只会在间谍注册后调用。在您的示例中, spyOn()
在调用 ngOnChanges()
之后执行,这就是问题所在。只需将 spyOn()
调用移到 ngOnChanges()
调用之前:
const selectSpy = spyOn(component, 'selectItem');
component.ngOnChanges(simpleChanges);
expect(selectSpy).toHaveBeenCalled();
我为 ngOnChanges
创建了一个测试,但即使它通过了函数,
有一个错误
Error: Expected spy selectItem to have been called.
这是我的 ngOnChange
ngOnChanges(changes: SimpleChanges): void {
const eventDataChange: SimpleChange = changes['selectEventData'];
if (eventDataChange) {
this.selectItem(eventDataChange.currentValue);
}
}
这是单元测试:
describe('ngOnChange()', () => {
it('this is a description', () => {
const selectDto = 'test';
const eventDataChange: SimpleChange = new SimpleChange(null, selectDto, false);
const simpleChanges: SimpleChanges = {
selectEventData: eventDataChange
};
component.ngOnChanges(simpleChanges);
const selectSpy = spyOn(component, 'selectItem');
expect(selectSpy).toHaveBeenCalled();
});
});
希望得到善意的回应!
谢谢!
spyOn
间谍只会在间谍注册后调用。在您的示例中, spyOn()
在调用 ngOnChanges()
之后执行,这就是问题所在。只需将 spyOn()
调用移到 ngOnChanges()
调用之前:
const selectSpy = spyOn(component, 'selectItem');
component.ngOnChanges(simpleChanges);
expect(selectSpy).toHaveBeenCalled();