2

У меня есть простой угловой компонент, как определено ниже. И я ищу, чтобы создать модульное тестирование с кармой, жасмином, чтобы пробежать этот компонент.Angular2 Testing Component с зависимым от поставщика

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

Однако я получил список странных ошибок ... Я предполагаю, что это связано с ConfigService поставщика в PropertyComponent, потому что, когда я снял зависимость поставщика, он прошел.

Кто-нибудь знает, как бороться с поставщиками зависимостей?

Спасибо!

ошибки:

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

Обратите внимание, что вам нужно импортировать Угловая это заплата describe, it, expect функции наряду с beforeEachProviders из angular2/testing. Я подчеркиваю это, потому что это легко забыть, и это приводит к ошибкам с довольно неинтуитивными сообщениями.

Смежные вопросы