Bab*_*ger 3 jestjs angular angular-spectator
我正在使用Spectator编写我的 Angular 8 测试并使用Jest来运行它们。根据自述文件,我可以setInput()用来将我的值分配给有效的字段名称。问题是在创建组件后正在验证输入,但在此之前我需要它,因为我在我的ngOnInit方法中使用它进行初始化:
// item.component.ts
@Input() items: Items[] = [];
ngOnInit(): void {
// do something with this.items
// read query param 'page' and use it for something
}
Run Code Online (Sandbox Code Playgroud)
和
// item.component.spec.ts
let spectator: SpectatorRouting<ItemComponent>;
const createComponent = createRoutingFactory({
component: ItemComponent,
queryParams: {page: 1}
});
beforeEach(() => spectator = createComponent());
it('test items', () => {
spectator.setRouteQueryParam('page', '2');
spectator.setInput("items", myItemsList);
});
Run Code Online (Sandbox Code Playgroud)
旁观者将正确设置 queryParampage和 Input items,但只有在组件已经创建之后。在组件创建期间ngOnInit将使用page == 1和 进行初始化items == []。
我可以在每个方法中创建旁观者组件并分别传递 queryParams,但我找不到在createRoutingFactory参数中传递输入的方法。
或者,我可以使用主机组件工厂来传递我的输入参数,但是我失去了传递我相信的查询参数的能力。
您可以在 createRoutingFactory 选项中设置 detectChanges=false。这将使 createComponent() 不会自动调用 onInit() ,并且在您的测试中,您应该在设置输入(或存根/模拟服务间谍)后调用 spectator.detectChanges():
// item.component.spec.ts
let spectator: SpectatorRouting<ItemComponent>;
const createComponent = createRoutingFactory({
component: ItemComponent,
queryParams: {page: 1},
detectChanges: false // set this to avoid calling onInit() automatically
});
beforeEach(() => spectator = createComponent());
it('test items', () => {
spectator.setRouteQueryParam('page', '2');
// spectator.inject(AnyService).doSomething.andReturn()... // stub services if needed
spectator.setInput("items", myItemsList);
spectator.detectChanges(); // Now onInit() will be called
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2142 次 |
| 最近记录: |