【问题标题】:Multiple providers Angular 2 test bed多个提供商 Angular 2 测试台
【发布时间】:2017-07-25 13:28:05
【问题描述】:

我似乎无法在 Angular 2 测试平台中注册多个提供者(服务)。我想要的只是为测试平台提供不止一项服务。这是我当前测试套件的示例。

export function main() {

  describe('Create Applications Component test suite:', () => {

    let fixtureComponent:any, nativeComponentElement:any;

    beforeEach(() => {

      return TestBed.configureTestingModule({
        imports: [
        ReactiveFormsModule,
        FormsModule
      ],
      declarations: [CreateApplicationComponent]
      }).overrideComponent(CreateApplicationComponent, {
        set: {
          providers: [
            {
              provide: injector,
              useClass: MockCreateApplicationService
            }
          ]
        }
      })
      .compileComponents().then(() => {
        fixtureComponent =  TestBed.createComponent(CreateApplicationComponent);
        nativeComponentElement = fixtureComponent.nativeElement;
        return fixtureComponent;
      });
    });

    it('component should work without errors', () => {
      expect(true).toBe(true);
    });

  });

}

我需要做的是这样的:

.overrideComponent(CreateApplicationComponent, {
    set: {
      providers: [
        {
          provide: injector,
          useClass: MockCreateApplicationService
        },
        {
          provide: providerB,
          useClass: SecondProvider
        }
      ]
    }
  })

【问题讨论】:

  • What I need to get to will be something like this: 似乎有什么问题?
  • 当我添加第二个提供者时,我收到了一个错误提示 no provider for form builder 所以我只是在 overrideComponent 方法中添加了表单构建器作为附加提供者,一切正常。谢谢你的提问!

标签: javascript unit-testing angular jasmine


【解决方案1】:

事实证明这是添加多个提供者的正确方法。我只是被我收到的缺少 formBuilder 提供程序的错误弄糊涂了,所以我添加了它,现在一切都按预期工作了。

解决方案:

.overrideComponent(CreateApplicationComponent, {
    set: {
      providers: [
        { provide: CreateApplicationService, useClass: MockCreateApplicationService },
        { provide: UserService, useClass: MockUserService },
        { provide: FormBuilder, useClass: FormBuilder }
      ]
    }
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2017-02-15
    • 2023-03-03
    相关资源
    最近更新 更多