1

早在 2016 年 6 月,我写了一篇关于如何测试 Angular 2 应用程序的文章。我使用angular2-seed作为起点。

https://raibledesigns.com/rd/entry/testing_angular_2_0_rc1

我决定使用 Angular CLI(来自它的 master 分支)重写本教程,它使用 Angular 2 RC5。我从我的一项测试中看到了一个奇怪的错误。

Error: Token must be defined!
    at new BaseException (/Users/mraible/ng2-demo/src/test.ts:1940:23 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/facade/exceptions.js:27:0)
    at new ReflectiveKey (/Users/mraible/ng2-demo/src/test.ts:27600:19 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/di/reflective_key.js:36:0)
    at KeyRegistry.get (/Users/mraible/ng2-demo/src/test.ts:27641:22 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/di/reflective_key.js:77:0)
    at Function.ReflectiveKey.get (/Users/mraible/ng2-demo/src/test.ts:27615:35 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/di/reflective_key.js:51:0)
    at ReflectiveInjector_.get (/Users/mraible/ng2-demo/src/test.ts:58418:62 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/di/reflective_injector.js:586:0)
    at NgModuleInjector.get (/Users/mraible/ng2-demo/src/test.ts:40942:52 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/src/linker/ng_module_factory.js:98:0)
    at TestBed.get (/Users/mraible/ng2-demo/src/test.ts:11910:47 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/testing/test_bed.js:269:0)
    at /Users/mraible/ng2-demo/src/test.ts:11916:61 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/testing/test_bed.js:275:46
    at Array.map (native)
    at TestBed.execute (/Users/mraible/ng2-demo/src/test.ts:11916:29 <- webpack:///Users/mraible/ng2-demo/~/@angular/core/testing/test_bed.js:275:0)

这是我的测试:

import { provide } from '@angular/core';
import { TestComponentBuilder } from '@angular/compiler/testing';

import { MockActivatedRoute } from '../shared/search/mocks/routes';
import { MockSearchService } from '../shared/search/mocks/search.service';

import { EditComponent } from './edit.component';
import { ActivatedRoute } from "@angular/router";
import { inject } from "@angular/core/testing/test_bed";

describe('Component: Edit', () => {
  var mockSearchService:MockSearchService;

  beforeEach(() => {
    mockSearchService = new MockSearchService();

    return [
      mockSearchService.getProviders(),
      provide(ActivatedRoute, { useValue: new MockActivatedRoute({ 'id': '1' }) })
    ];
  });

  it('should fetch a single record', inject([TestComponentBuilder], (tcb:TestComponentBuilder) => {
    return tcb.createAsync(EditComponent).then((fixture) => {
      let person = {name: 'Emmanuel Sanders', address: {city: 'Denver'}};
      mockSearchService.setResponse(person);

      fixture.detectChanges();
      // verify service was called
      expect(mockSearchService.getByIdSpy).toHaveBeenCalledWith(1);

      // verify data was set on component when initialized
      let editComponent = fixture.debugElement.componentInstance;
      expect(editComponent.editAddress.city).toBe('Denver');

      // verify HTML renders as expected
      var compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('h3')).toBe('Emmanuel Sanders');
    });
  }));
});

我已将此项目发布到 GitHub,因此您可以根据需要重现此问题:https ://github.com/mraible/ng2-demo 。

4

1 回答 1

1

马特,我已经复制了我认为是您工作代码的相关行,以帮助将来可能偶然发现这个问题的任何人。

TestBed您提到您的解决方法是从导入@angular/core/testing,我注意到您还遵循了注入模拟服务的指导,其方式也反映在角度测试文档和指南中。

我的修复有点不同;TestBed.configureTestingModule()这是由于我在该方法中提供的一项服务命名错误。

例如,在您的情况下,您实例化一个 newMockSearchService并将其传递到providers数组中mockSearchService,如下所示:{provide: SearchService, useValue: mockSearchService}.

就我而言,我传入了MockSearchService 类型(注意,实际类型,而不是实例),如下所示:({provide: SearchService, useValue: MockSearchService}注意大写)...

...然后得到一个服务实例,如下所示:mockSearchService = fixture.debugElement.injector.get(MockSearchService);.

但是,在我的例子中,我拼错了我传入的值,因为...injector.get(mockSearchService)它是一个无效的令牌,无法传递给注入器 getter。因此,我认为这个无效令牌错误是由 Karma 或测试过程中涉及的其他工具之一引发的,作为尝试访问或传递未定义令牌的全部案例。这个故事的道德,它可能与某处变量的错误命名有关。你的情况有点不同,但我几乎可以肯定它以某种方式相关:]。干杯!

你的工作代码

import { MockSearchService } from '../shared/search/mocks/search.service';
// other imports ...

describe('Component: Edit', () => {
    let mockSearchService: MockSearchService;
    // other service declarations...

    beforeEach(() => {
        mockSearchService = new MockSearchService();
        // other service instances...

        TestBed.configureTestingModule({
            // declarations...

            providers: [
                {provide: SearchService, useValue: mockSearchService},

                // other providers...
            ],

            // imports...
        });
    });

    // Tests ...

});
于 2016-10-28T21:43:00.210 回答