2016-04-15 121 views
2

我尝试用DI测试某个组件。我在寻找像堆栈/论坛等常见资源,但没有正确的答案我的问题(我找不到)。问题与角度2测试DI

当我尝试提供模拟依赖关系时,我得到错误:令牌必须定义 这是什么?我如何提供模拟依赖? (在提供的组件中存在一些下一级别的依赖关系 - 从httpconfig,所以我可以真实地创建它(因为他失败了自己的依赖关系......而且我认为我必须嘲笑这种依赖关系)

有我的测试

import {provide} from 'angular2/core'; 

import {setBaseTestProviders} from 'angular2/testing'; 
import { 
TEST_BROWSER_PLATFORM_PROVIDERS, 
TEST_BROWSER_APPLICATION_PROVIDERS 
} from 'angular2/platform/testing/browser'; 

import { beforeEach,beforeEachProviders,describe,expect, 
provide, 
it, 
inject, 
injectAsync, 
TestComponentBuilder, 
AsyncTestCompleter} from 'angular2/testing'; 


import {HTTPPatientsListService} from '../../shared/http_services/http_patients_list.service'; 
import {PatientsListComponent} from './patients_list.component'; 

class MockClass {} 

describe('Patients list Tests',() => { 
    beforeEachProviders(() => [ 
    provide(HTTPPatientsListService, {useClass: MockClass}) 
    ]); 

    it('Should defined recentPatientData ', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { 
    return tcb.createAsync(PatientsListComponent).then((componentFixture: ComponentFixture) => { 
     const element = componentFixture.nativeElement; 
     componentFixture.detectChanges(); 
    }); 
    })); 


}); 

有我的组件的部分(仅限于一部分。它是正确的工作,买他太长时间)

@Component({ 
    selector: 'cgm_patients_list', 
    templateUrl: `${MODULE_PATH}/patients_list.component.html`, 
    styleUrls: [`..${MODULE_PATH}/patients_list.component.css`], 
    pipes: [SearchPipe], 
    providers: [HTTPPatientsListService], 
    directives: [PatientsListDetailComponent] 
}) 

export class PatientsListComponent implements OnInit { 
    public recentPatientData; 

    private pipedPatientsData; 

    constructor(
    private patientsListService: HTTPPatientsListService) { 

    } 

感谢您的帮助...

P.S.错误是:

Chrome 49.0.2623 (Windows 7 0.0.0) Patients list Tests Should defined recentPatientData FAILED 
     Failed: Token must be defined! 
     Error: Token must be defined! 
      at new BaseException (D:/nucleous/client/src/www/node_modules/angular2/bundles/angular2.dev.js:7521:21) 
+0

@君特Zöchbauer的答案是正确的。另外我会建议检查https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/它有很好的例子。 – echonax

回答

1

你需要重写测试组件的供应商

return tcb 
.overrideProviders(PatientsListComponent, [provide(HTTPPatientsListService, {useClass: MockClass})]) 
.createAsync(PatientsListComponent) 
.then((componentFixture: ComponentFixture) => { 

参见https://angular.io/docs/ts/latest/api/testing/TestComponentBuilder-class.html

+0

嗨Gunter。很高兴见到你!我尝试使用你的提示,但得到了新的错误: * TypeError:tcb.createAsync(...)。overrideProviders不是函数* 是什么意思? – Velidan

+0

已解决:) createAsync必须在覆盖提供程序之后。感谢Gunter再次为您提供帮助和时间! _return tcb.overrideProviders(PatientsListComponent [provide(HTTPPatientsListService,{useClass:MockClass})]) .createAsync(PatientsListComponent)_ – Velidan

+0

Thanks!固定。复制粘贴错误: - / –