使用templateUrl时Angular2测试错误

时间:2016-12-07 09:28:35

标签: unit-testing angular testing

我正在根据文档为我的Angular2应用程序编写一些测试但是我遇到了一个我似乎无法解决的问题。尝试启动规范运行程序时出现以下错误:

Failed: This test module uses the component CategoriesComponent which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test.

我理解这种情况正在发生,因为我在组件中使用了单独的模板文件,但是我尝试了似乎不起作用的multilpe解决方案。

这是我正在测试的组件:

import { Component } from "@angular/core";

@Component({
    selector: 'categories-component',
    templateUrl: '/app/views/catalog/categories/categories-dashboard.html',
    moduleId: module.id
})

export class CategoriesComponent {
    title: 'Categories;
}

categories-dashboard.html文件:

<h1>{{ title }}</h1>

和我的组件测试模块:

import {TestBed, ComponentFixture, ComponentFixtureAutoDetect, async} from "@angular/core/testing";
import { By} from "@angular/platform-browser";
import { CategoriesComponent } from "../../../../components/catalog/categories/CategoriesComponent";
import { DebugElement } from "@angular/core";

let comp:    CategoriesComponent;
let fixture: ComponentFixture<CategoriesComponent>;
let de:      DebugElement;
let el:      HTMLElement;

describe('BannerComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ CategoriesComponent ],
            providers: [
                { provide: ComponentFixtureAutoDetect, useValue: true }
            ]
        });

        TestBed.compileComponents();

        fixture = TestBed.createComponent(CategoriesComponent);

        comp = fixture.componentInstance; // BannerComponent test instance

        // query for the title <h1> by CSS element selector
        de = fixture.debugElement.query(By.css('h1'));
        el = de.nativeElement;

    }));

    it('should display original title', () => {
        expect(el.textContent).toContain(comp.title);
    });
});

我已经尝试将TestBed.compileComponents()实现到组件中,但无论我把它放在哪里它似乎都不起作用。

任何人都可以看到为什么会出现这种错误或者指出解决方案的直接原因吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

compileComponents异步解析(因为它为模板创建了XHR),因此它返回一个promise。你应该在承诺的then回调中处理任何需要解决承诺的事情

TestBed.compileComponents().then(() =>{
    fixture = TestBed.createComponent(CategoriesComponent);

    comp = fixture.componentInstance; // BannerComponent test instance

    // query for the title <h1> by CSS element selector
    de = fixture.debugElement.query(By.css('h1'));
    el = de.nativeElement;
});