Angular Dependency Injection - @Injectable()在测试中失败,而@Inject()工作

时间:2018-01-03 22:10:31

标签: ruby-on-rails angular typescript dependency-injection webpacker

通用问题

我刚刚开始将带有角度5的webpacker添加到现有的rails应用程序中。一切都很好,除了测试DI的奇怪问题。

在使用浏览器创建时,我的Angular组件似乎正常工作,但在使用Jasmine / Karma进行测试时,Dependency Injector无法识别注入令牌。使用伪代码:

@Component({...})
export class SomeComponent {
  constructor(private service: SomeService) {}
}

以上内容适用于浏览器,但正在测试Error: Can't resolve all parameters for SomeComponent: (?).。到目前为止,我已经注意到它适用于所有@Injectable(),但是一旦我用显式的@Inject替换每个注入:

@Component({...})
export class SomeComponent {
  constructor(@Inject(SomeService) private service: SomeService) {}
}
一切正常(但显然很麻烦)。有什么明显可能导致这种情况吗?

实际代码

我使用HttpClient运行一个非常简单的服务:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import 'rxjs/add/operator/map'

@Injectable()
export class GeneralStatsService {
  constructor(
    private http : HttpClient
  ) {}

  getMinDate() {
    return this.http.get("/api/v1/general_stats/min_date")
      .map(r => new Date(r))
  }
}
当我导航到使用所述服务的组件时,

按预期工作。但是,在使用Jasmine进行测试时它不起作用:

import { TestBed } from "@angular/core/testing";
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { GeneralStatsService } from "./general-stats.service";


describe('GeneralStatsService', () => {
  let service : GeneralStatsService;
  let httpMock : HttpTestingController;

  beforeEach(()=> {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        GeneralStatsService
      ]
    })
  });

  beforeEach(() => {
    service = TestBed.get(GeneralStatsService);
    httpMock = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('getMinDate()', () => {
    let fakeResponse : string = "2015-03-05T12:39:11.467Z";

    it('returns instance of Date', (done) => {
      service.getMinDate().subscribe((result : Date) => {
        expect(result.getFullYear()).toBe(2015);
        expect(result.getMonth()).toBe(2); // January is 0
        expect(result.getDate()).toBe(5);
        done();
      });

      const req = httpMock.expectOne("/api/v1/general_stats/min_date");
      expect(req.request.method).toBe('GET');
      req.flush(fakeResponse);
    })
  });
});

如上所述,添加明确的@Inject(HttpClient)会修复测试,但我更愿意避免这种情况。

配置

噶:

const webpackConfig = require('./config/webpack/test.js');

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: [ 'jasmine' ],
    plugins: [
      require('karma-webpack'),
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('karma-spec-reporter')
    ],
    files: [
      'config/webpack/angular-bundle.ts'
    ],
    webpack: webpackConfig,
    preprocessors: {
      'config/webpack/angular-bundle.ts': ["webpack"]
    },
    mime: { "text/x-typescript": ["ts"]},
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    client: { clearContext: false },

    reporters: [ 'progress', 'kjhtml', 'coverage-istanbul' ],
    port: 9876,
    colors: true,

    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [ 'Chrome' ],
    singleRun: false,
    concurrency: Infinity
  })
};

配置/的WebPack / test.js:

const environment = require('./environment');
environment.plugins.get('Manifest').opts.writeToFileEmit = process.env.NODE_ENV !== 'test';
environment.loaders.set('istanbul-instrumenter', {
  test: /\.ts$/,
  enforce: 'post',
  loader: 'istanbul-instrumenter-loader',
  query: {
    esModules: true
  },
  exclude: ["node_modules", /\.spec.ts$/]
});

module.exports = environment.toWebpackConfig()

配置/的WebPack /角bundle.ts:

import 'zone.js/dist/zone'
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

jasmine.MAX_PRETTY_PRINT_DEPTH = 3;

getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

const context = (require as any).context('../../app/javascript', true, /\.spec\.ts$/);
context.keys().map(context);

tsconfig.json:

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "**/*.spec.ts",
    "node_modules",
    "vendor",
    "public",
    "config/**/*.ts"
  ],
  "compileOnSave": false
}

environment.js:

const environment = require('@rails/webpacker').environment;

const typescript =  require('./loaders/typescript');
const erb =  require('./loaders/erb');
const elm =  require('./loaders/elm');
const html =  require('./loaders/html');

environment.loaders.append('elm', elm);
environment.loaders.append('erb', erb);
environment.loaders.append('typescript', typescript);
environment.loaders.append('html', html);

module.exports = environment;

以防万一,装载者/打字稿:

module.exports = {
  test: /\.(ts|tsx)?(\.erb)?$/,
  use: [{
    loader: 'ts-loader'
  }]
}

5 个答案:

答案 0 :(得分:1)

尝试使用注射器和spyOn。

您必须创建一个模拟服务,而不使用' HttpClient',它具有您要模拟的服务的所有方法。然后使用spyOn,你可以返回你想要的东西。



TestBed.configureTestingModule({
      imports: [
        FormsModule,
        BrowserAnimationsModule
      ],
      providers: [
        {
          provide: YourService,
          useValue: mockedYourService
        }
      ]
      ....

 beforeEach(() => {
   fixture = TestBed.createComponent(YourTestingComponent);
   component = fixture.componentInstance;
   element = fixture.nativeElement;
   fixture.detectChanges();
 });

 ...
      
describe('methodName', () => {
  it('message to print',
    () => {
      const your_Service = fixture.debugElement.injector.get(YourService);
      spyOn(your_Service, 'methodName').and.returnValue(true);
        
        .....




希望这有帮助!

答案 1 :(得分:1)

您是否尝试在测试床配置中添加HttpClient作为提供程序?

TestBed
  .configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [GeneralStatsService,
      { provide: HttpClient, useValue: new HttpClient() }
    ]
  })

当有人a similar problem时,这是一个业绩开发者的建议。这也是Angular团队在您想要test a component with a dependency时推荐的内容。

答案 2 :(得分:1)

所以查看使用@Inject生成的JavaScript,以及仅使用@Component@Injectable生成的JavaScript(从完整的装饰器中提取):

__param(0, core_1.Inject(http_1.HttpClient)), // via @Inject
__metadata("design:paramtypes", [http_1.HttpClient]) // with @Component, @Injectable only

这是来自Angular 5的最新版本,但可能一直适用于2.您可以看到@Inject生成显式参数注入,否则注入仅依赖于元数据。这似乎强烈表明您的问题与您建议的emitDecoratorMetadata标志有关。

由于emitDecoratorMetadata不是默认启用选项,因此您的tsconfig.json可能不会包含在构建中。您可以使用ts-loader configFile属性明确指定其位置:

use: [{
        loader: 'ts-loader', 
        options: {
          configFile: 'tsconfig.json' // default
        }
      }] 

正如文档所述,指定文件名与相对路径不同。对于文件名ts-node将遍历文件夹树以尝试查找文件,但对于相对路径,它将仅尝试相对于您的条目文件。您还可以指定绝对路径(对于诊断,只丢弃硬编码路径可能很有用)。

如果失败了,我也可以通读Angular Webpack guide,其中详细介绍了awesome-typescript-loader的用法(是的,我必须在我认为它是真实的之前查找它)而不是{{ 1}}。它还明确定义了ts-loader路径,使用帮助器生成绝对路径。

答案 3 :(得分:0)

insetBy(dx:dy:)中是否排除了spec.ts文件的问题,以致tsconfig.json未应用于您的规范?

答案 4 :(得分:0)

我遇到了类似的问题,我通过在polyfills.js文件中导入core-js来解决此问题。 但我仍然不知道为什么会这样。

import 'core-js';