Asserting that a parent component exists in angular unit test

前端 未结 2 1020
一个人的身影
一个人的身影 2021-01-22 17:18

I have a top level component AppComponent and in it\'s template property it renders the element on the page. (

相关标签:
2条回答
  • 2021-01-22 17:34

    The error indicates that other units (ChildComponent) are involved in test. This error is caused by the fact that ChildComponent uses templateUrl, and such components may need to call compileComponents to compile them.

    Since AppComponent has template and not templateUrl, this makes a test synchronous and makes async helper unnecessary, also eliminates the need to use compileComponents.

    As explained in the guide,

    The TestBed.compileComponents method asynchronously compiles all the components configured in the testing module. In this example, the BannerComponent is the only component to compile. When compileComponents completes, the external templates and css files have been "inlined" and TestBed.createComponent can create new instances of BannerComponent synchronously.

    Unit test presumes that only one unit is tested, while other units are ignored, stubbed or mocked. This allows to keep a test isolated.

    Since undeclared components will result in error, they have to be stubbed:

      beforeEach(() => {
        @Component({ selector: 'child', template: '' })
        class DummyChildComponent {}
    
        TestBed.configureTestingModule({ declarations: [AppComponent, DummyChildComponent] });
      });
    

    An alternative to dummy component is CUSTOM_ELEMENTS_SCHEMA or NO_ERRORS_SCHEMA, which aren't suitable in tests because any possible error output may be valuable. And custom schema is more heavy-weight solution.

    0 讨论(0)
  • 2021-01-22 17:40

    You need to add the ChildComponent to your module:

      beforeEach(() => {
        TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] });
      });
    
    0 讨论(0)
提交回复
热议问题