我第一次使用Karma / Jasmine等来测试我的一个组件,并且主要跟随docs on testing。我的组件需要3个构造函数参数;
constructor(
private myService: MyService,
private renderer: Renderer,
private element: ElementRef
) { }
我试图模拟/存储基于this section of the docs的依赖关系,如下所示;
// Mocks/Stubs
const myServiceStub = {};
class MockElementRef {}
class MockRenderer {}
// beforeEach block
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
{ provide: ElementRef, useClass: MockElementRef },
{ provide: Renderer, useClass: MockRenderer },
{ provide: MyService, useValue: myServiceStub},
]
});
fixture = TestBed.createComponent(MyComponent);
});
尽管如此,每当我运行测试时,我都会收到以下错误;
Error: Can't resolve all parameters for MyComponent: (?, ?, ?).
at SyntaxError.ZoneAwareError (test.ts:9250:33)
at SyntaxError.BaseError [as constructor] (test.ts:44243:16)
at new SyntaxError (test.ts:44453:16)
at CompileMetadataResolver._getDependenciesMetadata (test.ts:61503:31)
我在这里缺少什么?谢谢!
答案 0 :(得分:4)
它可以由循环DI引起,尝试重构你的组件MyComponent以注入这样的服务:
constructor(@Inject(forwardRef(() => MyComponentService)) private myService: MyComponentService) {}