Angular 7:一个组件的测试失败与另一个组件有关

问题描述 投票:0回答:2

我正在测试一个组件,但测试失败,但失败的原因与我在测试中未声明的不同组件有关:

FooterComponent should create
Failed: Component SplashComponent is not part of any NgModule or the module has not been imported into your module.

enter image description here

FooterComponent:

@Component({
  selector: 'app-footer',
  templateUrl: './footer.html',
  styleUrls: ['./footer.scss']
})
export class FooterComponent implements OnInit {
  public date: number;
  public brandName: string;

  constructor(
    private config: Configuration) {
    }

  ngOnInit() {
    this.brandName = this.config.getConfigOption('brandName');
    this.date = new Date().getFullYear();
  }

}

测试:

describe('FooterComponent', () => {
  let component: FooterComponent;
  let fixture: ComponentFixture<FooterComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes(routes)
      ],
      declarations: [FooterComponent]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FooterComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

NGModule供参考:

@NgModule({
  declarations: [
    AppComponent,
    SplashComponent,
    FooterComponent,
   .....
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CollapseModule.forRoot(),
    ReactiveFormsModule,
    FormsModule,
    HttpClientModule
  ],
  schemas: [ NO_ERRORS_SCHEMA ],
  providers: [
   .....
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

对于其他组件的测试,重复同样的问题。

编辑:答案提到包含子组件的页脚模板,他们没有。但是,如果我将SplashComponent添加到测试声明中它确实有效,那么另一个组件就取而代之。

enter image description here

某处某处正在创建一个层次结构。

页脚模板:

<footer>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="links">
        <ul>
          <li><a [routerLink]="['/support']">Support</a></li>
          <li><a [routerLink]="['/terms']">Terms & Privacy</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <div class="copyright">
        <p>
          &copy; {{ date }} {{ brandName}}. Made with <span class="icon-favourites"></span> by 
          <a href="" target="_blank"></a>.
        </p>
      </div>
    </div>
  </div>
</div>
</footer>

编辑:2

App.component模板:

<app-header></app-header>
<main>
  <div class="container">
    <router-outlet></router-outlet>
  </div>
</main>
<app-footer></app-footer>
angular karma-jasmine
2个回答
1
投票

问题是由于您使用路线导入RouterTestingModule这一事实,很可能是与SplashComponent相关联的路径。

除非您计划使用具体组件测试特定路由,否则不应在qazxsw poi上配置路由。重构如下:

RouterTestingModule

1
投票

通过测试,您可以直接导入测试中的子组件,也可以模拟子组件。看到:

 beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [FooterComponent]
    })
    .compileComponents();
  }));
© www.soinside.com 2019 - 2024. All rights reserved.