Angular 2单元测试抛出错误'订阅'不是未定义的成员
问题描述:
我正在使用Angular 2应用程序中的茉莉花单元测试。Angular 2单元测试抛出错误'订阅'不是未定义的成员
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: Unable to get property 'subscribe' of undefined or null reference
这是我的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文件中有许多其他测试很好用,这是我试图编写的第一个测试,用于验证发送到我的服务的数据。
这个实现有什么问题?如果订阅在运行应用程序时已经运行,为什么单元测试失败?如果服务成功完成呼叫,我不必在乎,但我只想确保[取消服务]中的取消功能所收到的对象与预期一致。
编辑(响应由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();
});
答
如果在测试中使用一个服务,你必须在testBed的提供者中声明它,然后在beforeEach()
函数中实例化它
请参阅上面的我的编辑 – ganders