我收到这个错误:
错误:此测试模块使用正在使用“templateUrl”的组件MessagesComponent,但它们从未编译过。请在测试前调用“TestBed.compileComponents”。
当试图运行这个简单的测试Angular 2&Jasmine Test:
let comp: MessagesComponent;
let fixture: ComponentFixture<MessagesComponent>;
describe('MessagesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MessagesComponent ],
providers: [ {provide: DataService, useValue: {} } ]
})
.compileComponents(); // compile template and css
fixture = TestBed.createComponent(MessagesComponent);
comp = fixture.componentInstance;
});
it('example', () => {
expect("true").toEqual("true");
});
});
我想这可能是由于我的webpack测试配置的原因:
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'inline-source-map',
module: {
loaders: [
{ loader: 'raw', test: /\.(css|html)$/ },
{ exclude: /node_modules/, loader: 'ts', test: /\.ts$/ }
]
},
resolve: {
extensions: ['', '.js', '.ts'],
modulesDirectories: ['node_modules'],
root: path.resolve('.', 'src')
},
tslint: {
emitErrors: true
}
};
当您的模板未内联到组件中时,模板提取是异步的,因此您需要告诉Jasmine。更改
beforeEach(() => {
TestBed.configureTestingModule({ ... })
.compileComponents();
fixture = TestBed.createComponent(MessagesComponent);
comp = fixture.componentInstance;
});
至
beforeEach(async(() => {
TestBed.configureTestingModule({ ... })
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(MessagesComponent);
comp = fixture.componentInstance;
});
}));
由于您已经在使用webpack
,理论上您不必根据官方文档compileComponents()
调用here函数,因为webpack
将模板和css作为运行测试之前的自动构建过程的一部分。
你的模板/ css没有内联的一个可能原因是IDE(VisualStudio/WebStorm/IntelliJ
)自动将你的ts编译为js,而针对js/ts
文件的webpack加载器试图应用于已经编译的js文件而不是源ts文件。