如何对使用 CarouselModule 的 Angular 组件进行单元测试

时间:2021-05-16 07:47:03

标签: angular karma-jasmine

我创建了一个自定义组件 TorsoComponent,它使用另一个使用轮播的自定义组件 SponcerComponent。我需要测试 TorsoComponent 而不是轮播(轮播是我从 NPM 安装的依赖项)。所以我不关心这个,但它阻碍了我的躯干测试。这是我的代码。

package.json

“依赖项”:{ ... "ngx-owl-carousel-o": "^2.0.3" }

app.module.ts

import { CarouselModule } from 'ngx-owl-carousel-o';
...
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    CarouselModule,
    ...
  ]})

sponcers.component.ts

import { Component, OnInit } from '@angular/core';
import { OwlOptions } from 'ngx-owl-carousel-o';
@Component({
  ...
})
export class SponcersComponent {
  customOptions: OwlOptions = {
    ...
}

sponcers.component.html

<owl-carousel-o [options]="customOptions">
    <ng-template carouselSlide>
        <div id="template"><img class="....png"></div>
    </ng-template> 
    <ng-template carouselSlide>
    <div id="template"><img class="...png"></div>
        </ng-template>  
    <ng-template carouselSlide>
    ...
</owl-carousel-o>

现在是我需要帮助的规范文件。

torso.component.html

<app-sponcers></app-sponcers>

torso.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { SponcersComponent } from '../sponcers/sponcers.component';
import { TorsoComponent } from './torso.component';

fdescribe('TorsoComponent', ()=> {

  
  beforeEach(async()=> {
    TestBed.configureTestingModule({
      declarations: [TorsoComponent, SponcersComponent, CarouselModule ],
      imports: [TranslateModule.forRoot()]
    }).compileComponents();
  })

  it('should create', () => {
    const fixture = TestBed.createComponent(TorsoComponent);
    const app = fixture.debugElement.componentInstance;
  })
})

我被严格告知要避免使用 CUSTOM_ELEMENTS_SCHEMA。现在我收到此错误:

enter image description here

请指出我的错误。

1 个答案:

答案 0 :(得分:1)

您应该使用 imports 导入 CarouselModule 如下

import { TestBed, async } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { SponcersComponent } from '../sponcers/sponcers.component';
import { TorsoComponent } from './torso.component';

fdescribe('TorsoComponent', ()=> {

  
  beforeEach(async()=> {
    TestBed.configureTestingModule({
      imports: [CarouselModule], // <-- should be added here
      declarations: [TorsoComponent, SponcersComponent ],
      imports: [TranslateModule.forRoot()]
    }).compileComponents();
  })

  it('should create', () => {
    const fixture = TestBed.createComponent(TorsoComponent);
    const app = fixture.debugElement.componentInstance;
  })
})