没有 @Inject,Angular2 TestBed 找不到嵌套的提供者
Angular2 TestBed can't find nested provider without @Inject
我想测试以下服务:
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()
注释我的注入,但在正常情况下它工作得很好?
这可能不是人们正在寻找的答案;但是我重写了我的调试环境,这样输出现在是大量的 .spec.js 文件,而不是使用 Karma Typescript Pre-processor。我不确定为什么它不起作用;只有这样 对我有用。
我想测试以下服务:
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()
注释我的注入,但在正常情况下它工作得很好?
这可能不是人们正在寻找的答案;但是我重写了我的调试环境,这样输出现在是大量的 .spec.js 文件,而不是使用 Karma Typescript Pre-processor。我不确定为什么它不起作用;只有这样 对我有用。