什么是Jasmine中的TestBed?

5

我刚开始接触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 组件测试。 - Günter Zöchbauer
是的,但现在它显示“错误:无法创建组件AppComponent,因为它未被导入到测试模块中!” - fruitjs
你有查看过 https://angular.io/docs/ts/latest/guide/testing.html 吗? - Günter Zöchbauer
1个回答

13

在测试之前,请调用"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);
});

相关阅读


1
为什么我们要使用TestBed? - fruitjs
3
配置模块以适应测试环境。 - Paul Samsotha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接