2

我有一個簡單的angular2組件,如下定義。而且我正在尋找創建一個業力單元測試,茉莉花來貫穿這個組件。Angular2測試組件與供應商的依賴關係

@Component({ 
selector: 'property', 
template: require('./property.component.html'), 
directives: [Panel], 
providers: [ConfigService]}); 

export class PropertyComponent { 
config:any; 

constructor(config:ConfigService) { 
    this.config = config.getConfig(); 
} 
} 

這是我的測試規範文件。

describe('property component',() => { 

it('should have property page title', injectAsync([TestComponentBuilder], (tcb) => { 
return tcb.createAsync(PropertyComponent).then((fixture) => { 
    let propertyComp = fixture.componentInstance, 
     element = fixture.nativeElement; 

    expect(element.querySelector('h1').innerText).toBe('property page'); 
     }); 
    })); 
    }) 

但是我得到了奇怪的錯誤列表...我猜這是因爲在PropertyComponent的ConfigService的供應商,因爲當我刪除了供應商的依賴,它經歷。

有誰知道如何處理依賴提供程序?

謝謝!

錯誤:

[email protected]/config/spec-bundle.js:23435:38 
    [email protected]/config/spec-bundle.js:23424:42 
    [email protected]/config/spec-bundle.js:22937:38 
    [email protected]/config/spec-bundle.js:23641:51 
    [email protected]/config/spec-bundle.js:23587:42 
    [email protected]/config/spec-bundle.js:23573:35 
    [email protected]/config/spec-bundle.js:23463:53 
    [email protected]/config/spec-bundle.js:23435:38 
    [email protected]/config/spec-bundle.js:23424:42 
    [email protected]/config/spec-bundle.js:22924:35 
    [email protected]/config/spec-bundle.js:34694:44 
    [email protected]/config/spec-bundle.js:34371:33 
    viewFactory_HostPropertyComponent0 
    [email protected]/config/spec-bundle.js:35741:48 

回答

1

您需要在這種情況下使用beforeEachProviders

import {beforeEachProviders, describe, it, expect} from 'angular2/testing'; 
//...other imports... 

describe('property component',() => { 

    beforeEachProviders(()=> [ 
     ConfigService, //if you don't need to mock 
     provide(ConfigService, {useClass:MockConfigService}) // more typical 
    ]); 

    it('should have property page title', injectAsync([TestComponentBuilder], (tcb) => { 
    return tcb.createAsync(PropertyComponent).then((fixture) => { 
     //expectations... 
    }); 
    })); 
}) 

請注意,您需要導入角的FROM angular2/testing修補describe, it, expect功能與beforeEachProviders一起。我強調這一點,因爲很容易忘記這麼做,而且會導致失敗,並帶來不直觀的信息。