【问题标题】:Error: Please call "TestBed.compileComponents" before your test错误:请在测试前调用“TestBed.compileComponents”
【发布时间】:2017-03-18 21:09:11
【问题描述】:

我收到此错误:

错误:此测试模块使用了使用“templateUrl”的组件 MessagesComponent,但它们从未被编译。请在测试前调用“TestBed.compileComponents”。

当尝试运行这个简单的测试 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
    }
};

【问题讨论】:

    标签: angular jasmine webpack karma-jasmine angular2-template


    【解决方案1】:

    当您的模板没有内联到您的组件中时,模板获取是异步的,因此您需要告诉 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;
            });
    }));
    

    【讨论】:

    • 我应该以任何方式更改 it(...) 方法吗?
    • 仅当 it() 异步执行任何操作时,例如,如果它从服务获取数据。如果beforeEach() 需要异步但it() 不需要,那完全可以。
    • 哦,我错过了一些东西:...compileComponents().then(() =&gt; { ... }) 并在该函数中创建您的组件。您在加载和编译模板之前创建组件。
    • 请把代码完整地贴出来我真的不明白
    • 请不要忘记这个:)
    【解决方案2】:

    由于您已经在使用webpack,理论上您不必根据官方文档here 调用compileComponents() 函数,因为webpack 将模板和css 内联为前面的自动构建过程的一部分运行测试。

    您的模板/css 未内联的一个可能原因是 IDE(VisualStudio/WebStorm/IntelliJ) 自动将您的 ts 编译为 js,而针对 js/ts 文件的 webpack 加载器正试图在 上应用编译的 js 文件而不是源 ts 文件。

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2013-12-17
      • 2013-09-03
      • 2015-04-28
      相关资源
      最近更新 更多