ng-cli
生成的测试用例should create
失败,并出现以下错误:
Cannot read property 'length' of undefined
。
我在我的HTML中找到导致错误的行
items.component.html
<div *ngIf="items$ | async as items">
<input vaule="{{ items.colors.length }}" name="colors_count" /> Colors
</div>
在我拥有的组件内部:
items.component.ts
import * as fromItems from '../state';
export class ItemsComponent implements OnInit {
items$: Observable<Item>;
ngOnInit(): void {
this.items$ = this.store.pipe(select(fromItems.getCurrentItem));
}
}
items.component.spec.ts
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ItemModule, TestsModule ],
providers: [
ItemService,
NgForm,
ItemsEffects,
provideMockActions(() => actions),
]
})
.compileComponents();
}));
const item = new Item();
item.colors = [];
beforeEach(async(() => {
const id = '001318e4-b6f2-47d9-8816-c50a7b545784';
effects = TestBed.get(ItemsEffects);
const action = new itemActions.Load(id);
const completion = new itemActions.LoadSuccess(item);
fixture = TestBed.createComponent(ItemsComponent);
component = fixture.componentInstance;
component.items$ = of(item);
const service = fixture.debugElement.injector.get(ItemService);
spyOn(service, 'getItem').and.callThrough();
component.ngOnInit();
fixture.detectChanges();
}));
我正在使用ngrx-store在item$
生命周期挂钩中设置变量ngOnInit
。
在测试时,我试图在item.colors
中设置空白数组,以解决导致规范失败的上述length
错误。
但是,生命周期挂钩item.colors
覆盖了测试中ngOnInit
的设置值。
那么,我有什么办法可以监视items$
来等待值加载并在测试服中再次设置?