我有一个简单的子组件:
import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { HistorySession } from './models';
import { Observable } from 'rxjs';
@Component({
selector: 'app-history-info',
templateUrl: './history-info.component.html',
styleUrls: ['./history-info.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class HistoryInfoComponent implements OnInit {
@Input() sessionLoading: Observable<boolean>;
@Input() session: Observable<HistorySession>;
@Input() device: string;
constructor() {}
ngOnInit() {}
}
我的模板如下所示:
<div class="history__info-widget">
<span class="history__info-widget-title mat-caption">
START TIME
</span>
<span class="round-history__info-widget-content">{{
(session | async).startTime | date: 'HH:mm'
}}</span>
</div>
测试是这样的:
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HistoryInfoComponent } from './history-info.component';
describe('RoundHistoryInfoComponent', () => {
let component: HistoryInfoComponent;
let fixture: ComponentFixture<HistoryInfoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HistoryInfoComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HistoryInfoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
当我运行测试时,出现此错误:
历史信息组件 › 应创建
TypeError: Cannot read property 'startTime' of null
我是否必须模拟session.startTime属性的初始值或出了什么问题?如何模拟异步可观察输入((?
由于它是一个子组件,我建议不要传递可观察量,而最好只传递对象,让父对象管理订阅。
但是,如果您仍然想这样做,您可以使用 "of" 运算符并在 BeforeEach 中向其传递一个模拟对象 HistorySession - 像这样...
const mockHistorySession = {...}
beforeEach(() => {
fixture = TestBed.createComponent(HistoryInfoComponent);
component = fixture.componentInstance;
component.session = of(mockHistorySession);
fixture.detectChanges();
});
您还必须对其他输入执行此操作,否则您将遇到相同的问题。