【问题标题】:Angular2 testing error when using templateUrl使用 templateUrl 时 Angular2 测试错误
【发布时间】:2016-12-07 09:28:34
【问题描述】:

我正在根据文档为我的 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() 实现到组件中,但无论我把它放在哪里,它似乎都不起作用。

谁能看到为什么会发生这个错误或指出解决方案的方向?

谢谢!

【问题讨论】:

    标签: unit-testing angular testing


    【解决方案1】:

    compileComponents 异步解析(因为它为模板生成 XHR),因此它返回一个承诺。您应该在 promise 的 then 回调中处理任何需要解决 promise 的问题

    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;
    });
    

    【讨论】:

    • 太棒了。这解决了我的问题,但又引发了一个新问题!错误:超时 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调。我会调查
    猜你喜欢
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2016-06-12
    • 2017-04-27
    相关资源
    最近更新 更多