2016-11-04 34 views
6

我得到這個錯誤:角2茉莉:錯誤:您的測試之前,請撥打「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. 

當試圖運行這個簡單的測試角2 &茉莉花測試:

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

回答

15

當您的模板未內聯到您的組件中時,模板提取異步,因此您需要告訴Jasmine。既然你已經在使用webpack更改

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

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

我應該以任何方式更改它(...)方法嗎? – commonSenseCode

+0

僅當「it()」異步執行任何操作時(例如,如果它從服務中獲取數據)。如果'beforeEach()'需要異步,而'it()'不需要則完全沒問題。 – pe8ter

+0

奇怪我問,因爲我一直gettin相同的錯誤信息發佈在我原來的問題,但至少現在它說1失敗 – commonSenseCode

0

,理論上你不應該按照官方文檔here調用compileComponents()功能,因爲webpack內聯模板和CSS的部分在運行測試之前的自動構建過程。

你的模板/ CSS不內聯一個可能的原因是IDE(VisualStudio/WebStorm/IntelliJ)自動編譯您的TS JS和其目標爲js/ts文件的WebPack裝載機正試圖獲得有關已編譯的JS文件應用,而不是的源ts文件。