Angular2 TestBed无法在没有@Inject的情况下找到嵌套提供程序

时间:2017-01-31 16:34:50

标签: javascript unit-testing angular karma-runner

我想要测试以下服务:

import { Injectable } from "@angular/core";

import DepA from "./dep-a"

@Injectable()
export default class TestService {
    private readonly DepA: DepA;

    public constructor(depA: DepA) {
        this.DepA = depA;
    }
}

它依赖于另一项名为DepA的服务:

import { Injectable } from "@angular/core";

@Injectable()
export default class DepA {
}

我现在想要使用以下内容为TestService创建单元测试:

import { async, inject, TestBed } from '@angular/core/testing';

import DepA from "./dep-a";
import TestService from "./test-service";

class MockDepA {
}

describe("TestService", () => {
    beforeEach(() => {
        let dep = new DepA();

        TestBed.configureTestingModule({
            providers: [
                TestService,
                { provide: DepA, useValue: dep },
            ]
        });
    });

    it('should construct', inject(
        [TestService], (testService: TestService) => {
            expect(testService).toBeDefined();
        }));
});

这给了我以下错误:

$ ./node_modules/karma/bin/karma start karma.conf.js
Chrome 55.0.2883 (Windows 10 0.0.0) TestService should construct FAILED
        Error: Can't resolve all parameters for TestService: (?).
Chrome 55.0.2883 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) (0.033 secs / 0.021 secs)

当我将TestService的构造函数从public constructor(depA: DepA) {更改为public constructor(@Inject(DepA) depA: DepA) {时,它似乎工作正常。有没有理由说我必须在我的单元测试中用@Inject()注释我的注射,但是在正常情况下它没有用?

1 个答案:

答案 0 :(得分:0)

这可能不是人们正在寻找的答案;但我改写了我的调试环境,使得输出现在是多个.spec.js文件,而不是使用Karma Typescript预处理器。我不确定为什么它不起作用;只有这样它 才能为我工作。