简体   繁体   English

Angular 2单元测试抛出错误“订阅”不是未定义的成员

[英]Angular 2 unit test throwing error 'subscribe' is not a member of undefined

I'm working on my Jasmine unit tests in my Angular 2 app. 我正在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'
    });
});

This is throwing the error: 这引发了错误:

TypeError: Unable to get property 'subscribe' of undefined or null reference TypeError:无法获取未定义或空引用的属性“ subscribe”

Here's my cancelService.cancel function: 这是我的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);
}

And here's my controller/component for the actual cancel call: 这是我的实际取消呼叫的控制器/组件:

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);
        });
}

I have many other tests in this spec file that work great, this is the first test that I've tried to write to verify the data that gets sent to my service. 我在此spec文件中还有许多其他测试非常有效,这是我尝试编写的第一个测试,用于验证发送到我的服务的数据。

What's wrong with this implementation? 此实现有什么问题? If the subscribe works already when running the app, why does the unit test fail? 如果在运行应用程序时订阅已经生效,那么单元测试为什么会失败? I don't necessarily care [yet] if the service makes the call successfully, I just want to make sure that the object that the cancel function [in the cancel service] receives is as expected. 我不必在乎服务是否成功进行了调用,我只是想确保[取消服务中]取消功能接收的对象与预期的一样。

Edit (in response to the answer by user8019820): 编辑(响应于user8019820的回答):

Sorry, I should have included my two beforeEach functions: 抱歉,我应该包含我的两个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();
});

如果在测试中使用服务,则必须在beforeEach()提供程序中对其进行声明,然后在beforeEach()函数中将其实例化

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单元测试Angular 4收到错误`TypeError:无法读取未定义的属性&#39;subscribe&#39; - Unit test Angular 4 getting error `TypeError: Cannot read property 'subscribe' of undefined` Angular 单元测试 MockService 仍然抛出无法读取未定义的属性“订阅” - Angular Unit-Test MockService still throws Cannot read property 'subscribe' of undefined 如何在Angular中对嵌套的订阅方法进行单元测试? - How to unit test nested subscribe methods in Angular? 如何阅读 Angular 单元测试中的订阅? - How to read subscribe in Angular Unit Test? 角单元测试:调用另一个控制器中定义的方法会抛出“未定义”不是错误 - Angular unit testing: Calling a method defined in another controller is throwing 'undefined' is not an error 角度单元测试TypeError:无法读取未定义的属性“订阅” - Angular unit testing TypeError: Cannot read property 'subscribe' of undefined Karma 单元测试 EventEmitter 发射和订阅失败,无法读取未定义的属性“订阅” - Karma unit test EventEmitter emit and subscribe failed, Cannot read property 'subscribe' of undefined 角度测试&#39;订阅不是功能&#39; - Angular test 'subscribe is not a function' Angular 4单元测试获取错误-失败:无法读取未定义的属性“地图” - Angular 4 unit test get error - Failed: Cannot read property 'map' of undefined Karma单元测试&#39;undefined&#39;不是函数错误 - Karma unit test 'undefined' is not a function error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM