[英]Unit testing subscribe method using jasmine in angular project
I'm trying to test ngOnInit()
method for the component that has a subscribe
method: 我正在尝试对具有subscribe
方法的组件测试ngOnInit()
方法:
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. 请提出建议。
Fixed by implementing code as shown below: 通过实现如下代码进行修复:
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() 3.调用ngOnInit()
4.Make assertions using expect()
method 4,使用Expect expect()
方法进行断言
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.