问题
I'm trying to test ngOnInit()
method for the component that has a subscribe
method:
Component:
import { Component, OnInit} from '@angular/core';
import { SharedDataService } from './../services/shared-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private sharedDataService: SharedDataService,) { }
this.subscriptions = [];
ngOnInit() {
this.subscriptions.push(this.sharedDataService.getModel().subscribe(model => {
this.message=model.message
}));
}
}
}
Test Suite
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { XHRBackend } from '@angular/http';
describe('AppComponent Test', () => {
let component: any;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [SharedDataService , { provide: XHRBackend, useClass: MockBackend }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
it('test onInit function', () => {
component.ngOnInit();
spyOn(component.subscriptions,"push");
expect(component.subscriptions).toHaveBeenCalledWIth(component.sharedDataService.getModel());
});
});
But throwing error as "cannot spy on subscriptions".Is this is the procedure to test subscribe method. Please suggest.
回答1:
Fixed by implementing code as shown below:
- Imported import { Observable } from 'rxjs/Observable'; in my spec file
Created a spy for the method called inside subscription
spyOn(component.subscriptions, "push");
const spy = spyOn(sharedDataService, 'getModel').and. returnValue(Observable.of(“data to be returned by subscribe method”);
3.Call ngOnInit()
4.Make assertions using expect()
method
来源:https://stackoverflow.com/questions/48642641/unit-testing-subscribe-method-using-jasmine-in-angular-project