我正在使用Angular 2应用程序进行Jasmine单元测试 .
it('cancel object passed to the cancellation service is in the expected format for a cancel contract transaction', () => {
var cancelReason = new models.CancelReason();
cancelReason.cancelReasonCode = '165';
cancelReason.cancelReasonDescription = 'Because I said so';
component.subscriptionCancelReasons = [];
component.subscriptionCancelReasons.push(cancelReason);
component.cancellationsModel = new models.CancellationsModel();
component.cancellationsModel.groupNumber = 'xxxxxx';
component.cancellationsModel.billingUnit = 'xxxx';
component.cancellationsModel.memberId = 'xxxxxxxxx';
component.cancellationsModel.cancellationDate = '01/01/2020';
component.cancellationsModel.cancellationReason = '165';
component.cancellationsModel.cancelContract = true;
spyOn(cancelService, 'cancel');
component.cancel(); // initiate the cancel
expect(cancelService.cancel).toHaveBeenCalledWith({
memberKey: '000',
groupNumber: 'xxxxxx',
billingUnit: 'xxxx',
certificateNumber: 'xxxxxxxxx',
effectiveDate: '01/01/2020',
cancelReason: '165'
});
});
这是抛出错误:
TypeError:无法获取未定义或空引用的属性“subscribe”
这是我的 cancelService.cancel
功能:
cancel(cancelObject: any): any {
this.log('cancel', 'cancelObject: ' + JSON.stringify(cancelObject));
var contractsUrl = environment.contractsServiceUrl + '/contracts/cancel';
return this._http.put(contractsUrl, cancelObject)
.map(response => this.extractCancelResponse(response))
.catch(this.handleError);
}
这是实际取消呼叫的控制器/组件:
private executeCancel(transactionType:string, cancelObject: any) {
this.log('executeCancel', 'executing the cancel transaction...');
this.cancelService.cancel(cancelObject)
.subscribe(response => {
this.parseCancellationResponse(transactionType, response, cancelObject, true);
}, error => {
this.parseCancellationResponse(transactionType, error, cancelObject, false);
});
}
我在这个spec文件中有很多其他测试工作得很好,这是我尝试编写的第一个测试来验证发送到我的服务的数据 .
这个实现有什么问题?如果订阅在运行应用程序时已经有效,为什么单元测试失败?我不一定关心[如果]服务成功调用,我只是想确保取消函数[在取消服务中]接收的对象是预期的 .
Edit (in response to the answer by user8019820):
对不起,我应该包含我的两个 beforeEach
函数:
let component: ContractCancellationsComponent;
let fixture: ComponentFixture<ContractCancellationsComponent>;
let cancelService: CancelService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpModule,
FormsModule,
RouterTestingModule
],
providers: [
AppDataService,
ErrorService,
CancelService,
ContractsService
],
declarations: [
ContractCancellationsComponent,
WmHeaderComponent,
WmErrorListComponent,
WmStatusMessageComponent,
WmSpinnerComponent,
WmTimeoffsetPipe
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ContractCancellationsComponent);
component = fixture.componentInstance;
cancelService = fixture.debugElement.injector.get(CancelService);
fixture.detectChanges();
});
1 回答
如果在测试中使用服务,则必须在testBed的提供程序中声明它,然后在
beforeEach()
函数中实例化它