使用ReflectiveInjector更改测试中的提供程序

时间:2017-04-01 04:10:23

标签: angular

是否可以在同一上下文中使用ReflectiveInjector更改提供程序?我需要 B 在第二次测试中使用不同的值。 A& B是服务......

  let injector: ReflectiveInjector;
  beforeEach(() => {
    injector = ReflectiveInjector.resolveAndCreate([
      A, { provide: B, useValue: null }
    ]);
  });

  ...

  it('should be null', () => {
    const a = injector.get(A);
    expect(a.B).toBe(null)
  });

  it('shoul NOT be null', () => {
    const a = injector.get(A);
    // need something like this:
    // a.B = injector.CHANGE_B_PLEASE({ provide: B, useValue: true })
    expect(a.B).not.toBe(null)
  });

1 个答案:

答案 0 :(得分:1)

我的测试解决方案:

  let injector: ReflectiveInjector;
  setup((value) => {
    injector = ReflectiveInjector.resolveAndCreate([
      A, { provide: B, useValue: value }
    ]);
  });

  ...

  it('should be null', () => {
    setup(null);
    const a = injector.get(A);
    expect(a.B).toBe(null)
  });

  it('shoul NOT be null', () => {
    setup(true);
    const a = injector.get(A);
    const b = injector.get(B);
    expect(a.B).toBe(true)
    expect(b).toBe(true)
  });

有关详细信息,请查看: