Angular 2 Jasmine测试Observable

时间:2017-03-24 12:01:02

标签: angular typescript jasmine

我正在测试一个调用服务的组件。我想存根或模拟服务,以便它返回一个布尔值,并且我在subscribe函数的回调/成功函数中的组件变量被设置为这个模拟的布尔值。所以在我的组件中从我的组件调用welcomeService中的方法getBusinessDetails,这就是我遇到问题的地方。我希望isReturning值是伪造的,然后设置相应的组件变量。它返回Expecte dundefined为true。

 public getBusinessDetails(): void {
        this.welcomeService.getBusiness(this.businessId, 2017)
            .subscribe((isReturning) => {
                this.isReturningApplicant = isReturning;
                this.welcomeMessage = this.isReturningApplicant ? 'Welcome Back' : 'Welcome';
            });
    }


TestBed.configureTestingModule({
            declarations: [WelcomeComponent],
            imports: [ReactiveFormsModule],
            providers: [{ provide: SessionService, useValue: sessionServiceStub },
            { provide: WelcomeService, useValue: welcomeServiceStub }]
        });

describe('Gets  details', () => {
        beforeEach(() => {
            sessionServiceStub = {
                getSession: function () { return { businessId: 11111, agentId: 11111 } }
            }
            welcomeServiceStub = {
                getBusiness: function () { return { subscribe: () => Observable.of(true) } }
            };
        })

        it('get a returning customer', () => {
            component.ngOnInit();
            expect(component.isReturningApplicant).toBe(true);

        });

    })

1 个答案:

答案 0 :(得分:1)

让它在没有subscribe

的情况下返回observable
getBusiness: function () { return Observable.of(true) }

返回的Observable具有subscribe方法

getBusiness().subscribe()

getBusiness会返回Observable,然后您将调用更改为Observable.subscribe