我目前正在将单元测试集成到我的角度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 }}[
知道如何解决这个问题吗?
答案 0 :(得分:1)
在尝试创建组件之前,您需要compileComponents
。在beforeEach
中,您在调用compileComponents
之前尝试创建组件。只需删除它。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BasePage, LoginPage],
imports: [ReactiveFormsModule]
});
// const fixture = TestBed.createComponent(LoginPage);
// page = fixture.componentInstance;
});
修改强>
我猜这个问题与webpack有关
实际上,使用Webpack,您不需要调用compileComponents
,因为在使用Webpack时,您应该从templateUrl
获取模板并编译为{{ 1}}。您应该确保对于测试配置,您使用的是templates
。您可以查看this basic webpack configuration
答案 1 :(得分:0)
您需要调用beforeEach异步,因为模板提取过程是异步的。您还需要在调用configureTestingModule之后调用complileComponent,然后创建组件。 `
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [BasePage, LoginPage],
imports: [ReactiveFormsModule]
}).compileComponent().then(() => {
const fixture = TestBed.createComponent(LoginPage);
page = fixture.componentInstance;
})
}));
`