本文介绍了Angular 2& Jasmine:错误:请调用“TestBed.compileComponents”在你的考试之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误:

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&茉莉花测试:

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");
    });
});

我认为这可能是由于我的webpack测试配置的原因:

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


推荐答案

当您的模板未内联到模板时,模板提取是异步的你的组件,所以你需要告诉Jasmine。更改

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

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

这篇关于Angular 2&amp; Jasmine:错误:请调用“TestBed.compileComponents”在你的考试之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:00