gpt4 book ai didi

unit-testing - 使用 templateUrl 时 Angular2 测试错误

转载 作者:行者123 更新时间:2023-11-28 20:28:36 25 4
gpt4 key购买 nike

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

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.

我知道这是因为我在组件内使用单独的模板文件作为模板,但我已经尝试过似乎不起作用的多重解决方案。

这是我正在测试的组件:

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

任何人都可以看到为什么会发生此错误或指出我的解决方案吗?

谢谢!

最佳答案

compileComponents 异步解析(因为它为模板创建了一个 XHR),所以它返回一个 promise 。您应该在 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;
});

关于unit-testing - 使用 templateUrl 时 Angular2 测试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41013746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com