我目前正在将单元测试集成到我的 Angular 2 项目中。我能够测试服务,但在测试组件时遇到问题,这些组件使用 templateUrl 来获取外部模板。我猜问题与 webpack 有关,它错误地解析了路径/目录。这是我的测试文件。
import { TestBed, async } from '@angular/core/testing';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { BasePage } from '../../base/base.page';
import { LoginPage } from './login.page';
describe('Page: LoginPage', () => {
let page: LoginPage;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BasePage, LoginPage],
imports: [ReactiveFormsModule]
});
const fixture = TestBed.createComponent(LoginPage);
page = fixture.componentInstance;
});
it('Page: LoginPage should create a `FormGroup` comprised of `FormControl`s', async(() => {
TestBed.compileComponents().then(() => {
const fixture = TestBed.createComponent(LoginPage);
page = fixture.componentInstance;
page.ngOnInit();
expect(page).toBeDefined();
expect(page.loginForm instanceof FormGroup).toBe(true);
expect(Object.keys(page.loginForm.controls)).toEqual([
'email', 'password'
]);
});
}));
});
当我运行测试时,控制台上的输出如下:
WARN [web-server]: 404: /login.page.html
PhantomJS 2.1.1 (Linux 0.0.0) Page: LoginPage Page: LoginPage should create a `FormGroup` comprised of `FormControl`s FAILED
Error: This test module uses the component LoginPage which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test. in spec-bundle.js (line 15105)
我还尝试使用 template: require('raw!./login.page.html') 而不是 templateUrl: 'login.page.html' 加载模板。但由于模板解析错误,测试仍然失败:
Error: Template parse errors:
Unexpected closing tag "h4" (" col-lg-4 offset-lg-4\">\n <h4 class=\"card-title\">{{ 'pages.login.title' | translate }}[
知道如何解决这个问题吗?
最佳答案
在尝试创建组件之前,您需要compileComponents
。。在 beforeEach
中,您尝试在调用 compileComponents
之前创建组件。只需删除它即可。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BasePage, LoginPage],
imports: [ReactiveFormsModule]
});
// const fixture = TestBed.createComponent(LoginPage);
// page = fixture.componentInstance;
});
编辑
I guess the problem is related to webpack
实际上,使用 Webpack 你不需要调用 compileComponents
,因为使用 Webpack 时,你应该从 templateUrl
获取模板> 并编译成模板
。您应该确保对于测试配置,您使用的是'angular2-template-loader'
。您可以看看this basic webpack configuration
关于angular - Jasmine + Angular2 : This test module uses the component Login which is using a "templateUrl", 但它们从未被编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242249/