Angular2 unit test with @Input()

前端 未结 4 1341
广开言路
广开言路 2020-12-23 15:53

I\'ve got a component that uses the @Input() annotation on an instance variable and I\'m trying to write my unit test for the openProductPage() met

4条回答
  •  一个人的身影
    2020-12-23 16:42

    You need to set the product value on the component instance after it has been loaded within your test.

    As a sample here is a simple component within an input that you can use as a foundation for your use case:

    @Component({
      selector: 'dropdown',
      directives: [NgClass],
      template: `
        
    `, }) export class DropdownComponent { @Input('open') open: boolean = false; ngOnChanges() { console.log(this.open); } }

    And the corresponding test:

    it('should open', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
      return tcb.createAsync(DropdownComponent)
      .then(fixture => {
        let el = fixture.nativeElement;
        let comp: DropdownComponent = fixture.componentInstance;
    
        expect(el.className).toEqual('');
    
        // Update the input
        comp.open = true; // <-----------
    
        // Apply
        fixture.detectChanges(); // <-----------
    
        var div = fixture.nativeElement.querySelector('div');
        // Test elements that depend on the input
        expect(div.className).toEqual('open');
      });
    }));
    

    See this plunkr as a sample: https://plnkr.co/edit/YAVD4s?p=preview.

提交回复
热议问题