【问题标题】:What is TestBed in JasmineJasmine 中的 TestBed 是什么
【发布时间】:2016-10-06 06:10:19
【问题描述】:

我是 Angular 2 的 Jasmine 新手,在编写测试用例时我经常使用 TestBed 对象并收到错误:Please call "TestBed.compileComponents" before your test.

我该如何解决这个错误?

@Component({
  moduleId:module.id,
    selector: 'my-app',
    templateUrl: 'app-component.html',

})

【问题讨论】:

  • 你试过打电话给TestBed.compileComponents()吗? TestBed 是一个模拟环境,可以在没有浏览器的情况下运行 Angular2 组件测试。
  • 是的,但现在显示错误:无法创建组件 AppComponent 因为它没有导入到测试模块中!

标签: angular jasmine karma-jasmine angular2-testing


【解决方案1】:

请在测试前调用“TestBed.compileComponents”

使用templateUrl测试组件时需要此调用

错误:无法创建组件 AppComponent,因为它没有导入到测试模块中!

您需要在每次测试之前配置TestBed,添加测试所需的任何组件、模块和服务。这就像从头开始配置一个普通的@NgModule,但你只需添加你需要的。

import { async, TestBed } from '@angular/core/testing';

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ AppComponent ],
    providers: [],
    imports: []
  })
  .compileComponents();
}));

it('...', () => {
  let fixture = TestBed.createComponent(AppComponent);
});

另见

【讨论】:

  • 我们为什么要使用 TestBed?
  • 为测试环境配置模块。
猜你喜欢
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多