2016-12-07 82 views
1

根據文檔我正在爲我的Angular2應用程序編寫一些測試,但我遇到了一個我似乎無法修復的問題。嘗試啓動規範亞軍時,我得到了以下錯誤:使用templateUrl時Angular2測試錯誤

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

我明白這是因爲我使用的組件內的模板一個單獨的模板文件發生,但我jhave試圖multilpe解決方案,似乎不上班。

這裏是我的測試組件:

import { Component } from "@angular/core"; 

@Component({ 
    selector: 'categories-component', 
    templateUrl: '/app/views/catalog/categories/categories-dashboard.html', 
    moduleId: module.id 
}) 

export class CategoriesComponent { 
    title: 'Categories; 
} 

類別-dashboard.html文件:

<h1>{{ title }}</h1> 

和我的部件測試模塊:

import {TestBed, ComponentFixture, ComponentFixtureAutoDetect, async} from "@angular/core/testing"; 
import { By} from "@angular/platform-browser"; 
import { CategoriesComponent } from "../../../../components/catalog/categories/CategoriesComponent"; 
import { DebugElement } from "@angular/core"; 

let comp: CategoriesComponent; 
let fixture: ComponentFixture<CategoriesComponent>; 
let de:  DebugElement; 
let el:  HTMLElement; 

describe('BannerComponent',() => { 
    beforeEach(async(() => { 
     TestBed.configureTestingModule({ 
      declarations: [ CategoriesComponent ], 
      providers: [ 
       { provide: ComponentFixtureAutoDetect, useValue: true } 
      ] 
     }); 

     TestBed.compileComponents(); 

     fixture = TestBed.createComponent(CategoriesComponent); 

     comp = fixture.componentInstance; // BannerComponent test instance 

     // query for the title <h1> by CSS element selector 
     de = fixture.debugElement.query(By.css('h1')); 
     el = de.nativeElement; 

    })); 

    it('should display original title',() => { 
     expect(el.textContent).toContain(comp.title); 
    }); 
}); 

我有試圖將TestBed.compileComponents()實現到組件中,但無論我把它放在哪裏,似乎都沒有工作。

任何人都可以看到爲什麼會發生此錯誤或指向我的解決方案directoin?

謝謝!

回答

2

compileComponents異步解析(因爲它爲模板創建一個XHR),所以它返回一個promise。您應該處理任何需要解決承諾的內容,then承諾回調

TestBed.compileComponents().then(() =>{ 
    fixture = TestBed.createComponent(CategoriesComponent); 

    comp = fixture.componentInstance; // BannerComponent test instance 

    // query for the title <h1> by CSS element selector 
    de = fixture.debugElement.query(By.css('h1')); 
    el = de.nativeElement; 
}); 
+0

好極了。這解決了我的問題,但拋出了一個新的!錯誤:超時 - 異步回調未在由jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超時內調用。我會調查 – devoncrazylegs

相關問題