我尝试用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) {
}
感谢您的帮助...
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 :(得分: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