【发布时间】:2016-08-07 02:57:18
【问题描述】:
我尝试使用 DI 测试某些组件。我查看了堆栈/论坛等公共资源。但我的问题没有正确答案(我找不到)。
当我尝试提供模拟依赖时,我收到错误:必须定义令牌 这是什么?我如何提供模拟依赖? (在提供的组件中存在一些下一级依赖项 - 来自 http 和 config,所以我可以真正创建它(因为他没有自己的依赖项就失败了......而且我认为我必须模拟这个依赖)。
这是我的测试
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) {
}
感谢您的帮助...
附:错误是:
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)
【问题讨论】:
-
@Günter Zöchbauer 的回答是正确的。另外我建议检查developers.livechatinc.com/blog/… 它有很好的例子。
标签: unit-testing testing dependency-injection angular