我正在用角度8编写测试,以检查是否已调用component方法。就我而言,我正在检查方法 调用removeSettlementConfirmation。我不确定callThrough或返回空obserable是否是最好的测试方法 如果该方法称为
如果我写
spyOn(component, 'removeSettlementConfirmation').and.callThrough();
我收到错误TypeError:无法读取未定义的属性'subscribe'
但是如果我写
spyOn(component, 'removeSettlementConfirmation').and.returnValue({ subscribe: () => {} });
错误消失了。
测试这种方法的正确方法是什么?
单元测试
fit('removeSettlementConfirmation should be called', () => {
let clientCompanyOpiId = 10;
let title = `Delete Settlement Account`;
let message = `Are you sure you want to delete this OPI account?`;
let testConfirmModal = ({
title: 'Delete Settlement Account',
message: 'Are you sure you want to delete this OPI account?'
} as ConfirmModalComponent);
component.confirmModal = testConfirmModal;
spyOn(component, 'removeSettlementConfirmation').and.returnValue({ subscribe: () => {} });
spyOn(clientService, 'getNumberOfTradesWhereOPIIsSetOn').and.returnValue({ subscribe: () => {} });
component.removeSettlementConfirmation(clientCompanyOpiId);
expect(component.removeSettlementConfirmation).toHaveBeenCalled();
});
组件代码
removeSettlementConfirmation(clientCompanyOpiId: number): void {
this.clientService.getNumberOfTradesWhereOPIIsSetOn(clientCompanyOpiId)
.subscribe(
data => {
const assignedTrades = data;
const trades = +assignedTrades > 1 ? 's' : '';
const message = assignedTrades
? `This OPI account is set on ${assignedTrades} trade${trades}. Are you sure you want to delete it?`
: `Are you sure you want to delete this OPI account?`;
const title = `Delete Settlement Account`;
this.confirmModal.openModal(title, message, clientCompanyOpiId);
},
error => {
this.alertService.showMessage("Error", "Unable to get Associated Trades for Settlement Account", MessageSeverity.error);
});
}
答案 0 :(得分:0)
and.returnValue():
可以使间谍返回一个预设值/固定值(无需使用and.callThrough())
调用实际方法。这可以通过将spyOn()
函数与and.returnValue().
链接来实现。
fit('removeSettlementConfirmation should be called', () => {
let clientCompanyOpiId = 10;
let title = `Delete Settlement Account`;
let message = `Are you sure you want to delete this OPI account?`;
let testConfirmModal = ({
title: 'Delete Settlement Account',
message: 'Are you sure you want to delete this OPI account?'
} as ConfirmModalComponent);
component.confirmModal = testConfirmModal;
spyOn(component, 'removeSettlementConfirmation').and.returnValue("mock response"); // with returnValue() you should return the actual mockResponse
spyOn(clientService, 'getNumberOfTradesWhereOPIIsSetOn').and.returnValue("test"); // with returnValue() you should return the actual mockResponse
component.removeSettlementConfirmation(clientCompanyOpiId);
expect(component.removeSettlementConfirmation).toHaveBeenCalled();
// you can verify by calling the methods and expected response
const response = component.removeSettlementConfirmation();
expect(response).toEqaul("mock response");
});