模拟服务时 Angular2 测试失败

Angular2 test fail when mocking a service

尝试测试具有调用 rest API 的服务依赖项的组件,制作了该服务的模拟版本,其中 class 扩展了真实服务。

现在,如果我用模拟的提供程序覆盖提供程序,业力报告器会出现奇怪的错误,首先是 404 表示 2 个不存在的文件(实际上不应该存在),然后是“{originalErr: {}}”。我的意思是至少告诉我我做错了什么:)

我的测试服:

 describe('App: HeaderComponent', () => {
      it('should get categories on initialization', 
        async(
          inject([TestComponentBuilder], (builder: TestComponentBuilder) => {
            let fixture: ComponentFixture<HeaderComponent>;
            expect(builder).toBeDefined();
            return builder
              .overrideProviders(HeaderComponent, [{provide: CategoryService, useClass: MockCategoryService}])
              .createAsync(HeaderComponent).then((_fixture) => {
                fixture = _fixture;
                let $el = fixture.debugElement;
                let el = $el.nativeElement;
                let component = $el.componentInstance;
                component.ngOnInit();
                fixture.detectChanges();
                expect(el.querySelector('a')).toHaveText('Electric');
              });
          })
        )
      );
    });

输出:

01 08 2016 11:58:29.684:WARN [karma]: No captured browser, open http://localhost:9876/
01 08 2016 11:58:29.713:INFO [karma]: Karma v1.1.2 server started at http://localhost:9876/
01 08 2016 11:58:29.718:INFO [launcher]: Launching browser Chrome with unlimited concurrency
01 08 2016 11:58:29.729:INFO [launcher]: Starting browser Chrome
01 08 2016 11:58:32.277:INFO [Chrome 52.0.2743 (Windows 10 0.0.0)]: Connected on socket /#Semtu7s7yqM-TW0GAAAA with id 14496897
01 08 2016 11:58:35.315:WARN [web-server]: 404: /base/dist/app/shared/services.js
01 08 2016 11:58:35.318:WARN [web-server]: 404: /base/dist/app/shared/services/mocks.js
Chrome 52.0.2743 (Windows 10 0.0.0) ERROR
  {
    "originalErr": {}
  }

如果我删除测试通过的行(但不执行 "then(...)" 代码块):

overrideProviders(HeaderComponent, [{provide: CategoryService, useClass: MockCategoryService}])

好吧,万一有人遇到同样的问题,结果应该是导入 "ts" 文件本身,而不是通过桶。意思是你应该这样写:

import { CategoryService } from '../../shared/services/category/category.service';
import { MockCategoryService } from '../../shared/services/category/category.service.mock';

而不是

import { CategoryService, MockCategoryService } from '../../shared/services/category';

即使导出文件的目录中有 index.ts。

奇怪,嗯?

还有不执行异步操作的问题,不知道为什么