我正在 Jasmine 单元测试一个使用 Observables 的角度组件。我的组件有我正在测试的生命周期挂钩:
ngOnInit() {
this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
}
我有一个测试可以确保 getCellOEE 已被调用,但现在我想检查当可观察值解析为新值时是否调用 updateChart。这是我到目前为止所拥有的:
let fakeCellService = {
getCellOEE: function (value): Observable<Array<IOee>> {
return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
}
};
describe('Oee24Component', () => {
let component: Oee24Component;
let service: CellService;
let injector: Injector;
let fixture: ComponentFixture<Oee24Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Oee24Component],
providers: [{ provide: CellService, useValue: fakeCellService }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Oee24Component);
component = fixture.componentInstance;
injector = getTestBed();
service = injector.get(CellService)
fixture.detectChanges();
spyOn(service, 'getCellOEE').and.returnValue({ subscribe: () => { } });
spyOn(component, 'updateChart');
});
it('should get cell oee on init', () => {
component.ngOnInit();
expect(service.getCellOEE).toHaveBeenCalled();
});
it('should update chart on new data', () => {
component.ngOnInit();
expect(component.updateChart).toHaveBeenCalled();
});
});
但是,我收到错误:
chrome 56.0.2924 (Windows 10 0.0.0) Oee24Component 应更新新数据图表失败
预期已调用间谍 updateChart。
据推测,这是一个时间问题,因为在测试检查时可观察到的问题不一定得到解决?如果是这种情况,我该如何正确设置?
Update:
这是我的组件:
@Component({
selector: 'app-oee24',
templateUrl: './oee24.component.html',
styleUrls: ['./oee24.component.css']
})
export class Oee24Component implements OnInit {
public barChartData: any[] = [{ data: [], label: 'OEE' }];
constructor(public dataService: CellService) { }
ngOnInit() {
this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
}
updateChart(data: Array<IOee>) {
this.barChartData[0].data = data.map(val => val.val);
}
}