简体   繁体   English

Angular2组件测试-错误:无法解析所有参数

[英]Angular2 Component test - Error: Can't resolve all parameters

I'm working on testing one of my components for the first time using Karma/Jasmine etc and have been mostly following along with the docs on testing . 我正在第一次使用Karma / Jasmine等工具测试我的一个组件,并且一直关注测试文档 My component requires 3 constructor arguments; 我的组件需要3个构造函数参数。

constructor(
  private myService: MyService,
  private renderer: Renderer,
  private element: ElementRef
) { }

I have attempted to mock/stub those dependencies based on this section of the docs as follows; 我已经尝试根据文档的这一部分模拟/存根那些依赖关系,如下所示;

// 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);
});

Despite this, whenever I run my tests I get the following error; 尽管如此,每当我运行测试时,都会出现以下错误;

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)

What am I missing here? 我在这里想念什么? Thank you! 谢谢!

它可能是由循环DI引起的,请尝试将您的组件MyComponent重构为注入服务,如下所示:

constructor(@Inject(forwardRef(() => MyComponentService)) private myService: MyComponentService) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM