我尝试为subscribe
方法的组件测试 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
}));
}
}
}
方法:
组件:
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());
});
});
测试套件
strtotime()
但抛出错误,因为&#34;无法监视订阅&#34;。这是测试订阅方法的过程。请建议。
答案 0 :(得分:0)
通过实现如下所示的代码来修复:
为内部订阅
中的方法创建了一个间谍 spyOn(component.subscriptions, "push");
const spy = spyOn(sharedDataService, 'getModel').and.
returnValue(Observable.of(“data to be returned by subscribe method”);
3.Call ngOnInit()
4.使用expect()
方法