Angular2 unit test with @Input()

前端 未结 4 1340
广开言路
广开言路 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:20

    I usually do something like:

    describe('ProductThumbnail', ()=> {
      it('should work',
        injectAsync([ TestComponentBuilder ], (tcb: TestComponentBuilder) => {
          return tcb.createAsync(TestCmpWrapper).then(rootCmp => {
            let cmpInstance: ProductThumbnail =  
                   rootCmp.debugElement.children[ 0 ].componentInstance;
    
            expect(cmpInstance.openProductPage()).toBe(/* whatever */)
          });
      }));
    }
    
    @Component({
     selector  : 'test-cmp',
     template  : '',
     directives: [ ProductThumbnail ]
    })
    class TestCmpWrapper { 
        mockProduct = new Product(); //mock your input 
    }
    

    Note that product and any other fields on the ProductThumbnail class can be private with this approach (which is the main reason I prefer it over Thierry's approach, despite the fact that it's a little more verbose).

提交回复
热议问题