Error: Please call "TestBed.compileComponents" before your test

Error: Please call "TestBed.compileComponents" before your test

我收到这个错误:

Error: This test module uses the component MessagesComponent which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test.

当尝试 运行 这个简单的测试时 Angular 2 & Jasmine 测试:

  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,理论上你不应该根据官方文档here调用compileComponents()函数,因为webpack内联模板和css 作为 运行 测试之前的自动构建过程的一部分。

您的 template/css 未内联的一个可能原因是 IDE(VisualStudio/WebStorm/IntelliJ) 自动将您的 ts 编译为 js 以及针对 js/ts 的 webpack 加载程序文件正试图应用于 已编译的 js 文件而不是源 ts 文件。