【问题标题】:Issue with angular2 tesing DI角度 2 测试 DI 的问题
【发布时间】:2016-08-07 02:57:18
【问题描述】:

我尝试使用 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) {

  }

感谢您的帮助...

附:错误是:

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)

【问题讨论】:

标签: unit-testing testing dependency-injection angular


【解决方案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

【讨论】:

  • 你好,甘特。很高兴见到你!我尝试使用您的提示,但出现新错误:TypeError: tcb.createAsync(...).overrideProviders is not a function 这是什么意思?
  • 已解决 :) createAsync 必须在覆盖提供程序之后。再次感谢 Gunter 的帮助和时间! return tcb.overrideProviders(PatientsListComponent [provide(HTTPPatientsListService, {useClass: MockClass})]) .createAsync(PatientsListComponent)
猜你喜欢
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2019-01-27
  • 1970-01-01
  • 2020-02-24
相关资源
最近更新 更多