Error: Please call “TestBed.compileComponents” before your test

时间秒杀一切 提交于 2019-12-04 19:12:05

问题


I'm getting this error:

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.

When trying to run this simple test 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");
    });
});

I think it might be due to something with my webpack test configuration:

'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
    }
};

回答1:


Template fetching is asynchronous when your templates are not inlined into your components, so you need to tell Jasmine that. Change

beforeEach(() => {
    TestBed.configureTestingModule({ ... })
        .compileComponents();
    fixture = TestBed.createComponent(MessagesComponent);
    comp = fixture.componentInstance;
});

to

beforeEach(async(() => {
    TestBed.configureTestingModule({ ... })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(MessagesComponent);
            comp = fixture.componentInstance;
        });
}));



回答2:


Since you are already using webpack, theoretically you should not have to call the compileComponents() function according to the official doc here, because webpack inlines templates and css as part of the automated build process that precedes running the test.

One possible reason that your template/css are not inlined is the IDE(VisualStudio/WebStorm/IntelliJ) auto compiles your ts to js and the webpack loaders which target for js/ts files are trying to get applied on the already compiled js files instead of the source ts files.



来源:https://stackoverflow.com/questions/40432734/error-please-call-testbed-compilecomponents-before-your-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!