【问题标题】:Spectator Angular testing - pass input before ngOnInit观众角度测试 - 在 ngOnInit 之前传递输入
【发布时间】:2020-04-01 08:35:56
【问题描述】:

我使用Spectator 编写我的Angular 8 测试并使用Jest 运行它们。根据the README,我可以使用setInput() 将我的值分配给有效的字段名称。问题是在创建组件之后验证输入,但在此之前我需要它,因为我在 ngOnInit 方法中使用它进行初始化:

// item.component.ts

@Input() items: Items[] = [];

ngOnInit(): void {
    // do something with this.items
    // read query param 'page' and use it for something
}

// 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); 
});

旁观者将正确设置 queryParam page 和 Input items,但前提是组件已经创建。在组件创建期间ngOnInit 将使用page == 1items == [] 进行初始化。

我可以在每个方法中创建旁观者组件并分别传递 queryParams,但我找不到在 createRoutingFactory 参数中传递输入的方法。

或者,我可以使用 a host component factory 传递我的输入参数,但我相信我无法传递查询参数。

【问题讨论】:

    标签: angular jestjs angular-spectator


    【解决方案1】:

    您可以在 createRoutingFactory 选项中设置 detectChanges=false。这将使 createComponent() 不会自动调用 onInit(),并且在您的测试中,您应该在设置输入(或 stubing/mocking services spys)后调用 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
    });
    

    【讨论】:

    • 是的,我也是后来才知道的。我忘记了这个问题,否则我会更新它。我会将您的解决方案标记为答案,因为它比再次调用 ngOnInit 更干净。干杯。
    【解决方案2】:

    我找到了这个问题的答案。原来很简单,设置完 mocks 等参数后,再次调用ngOnInit 重新初始化组件即可。所以我的测试方法变成了:

    // 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); 
        spectator.component.ngOnInit(); // Now the component is reinitialized and the input will contain myItemsList
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 2020-02-29
      • 2019-03-25
      • 2020-10-22
      • 2018-09-24
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多