Angular 9 TestBed.inject & 提供商覆盖

Angular 9 TestBed.inject & Provider Overrides

当使用 provider override 时,现在 TestBed.get 已在 Angular 9

中弃用,下面的替代方案是什么
TestBed.configureTestingModule({
  providers: [{ provide: MyClass, useClass: MyStub}]
});

const obj : MyStub = TestBed.get(MyClass);

真的是这样还​​是有更好的办法?

const obj : MyStub = TestBed.inject(MyClass) as unknown as MyStub;

出于所有意图和目的,您的 MyStub 至少应该是一个 Partial 或 class 来扩展它试图模拟的 class,否则您的测试有点 'wrong',所以如果是这种情况,您可以这样做:

const obj = TestBed.inject(MyClass);

如果你的存根上有不同的属性或不同的函数签名,你也可以这样做:

const obj = TestBed.inject<MyStub>(MyClass as any);

但一般来说,您的模拟应该(部分)与其模拟的对象共享相同的签名,这也意味着不需要强制转换

let valueServiceSpy: jasmine.SpyObj<ValueService>;

beforeEach(() => {
  const spy = jasmine.createSpyObj('ValueService', ['getValue']);

  TestBed.configureTestingModule({
    providers: [
      { provide: ValueService, useValue: spy }
    ]
  });
  // This is new way to inject Spied Service
  valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>; 
});

然后在测试中

it('#getValue should return stubbed value from a spy', () => {
  valueServiceSpy.getValue.and.returnValue(yourValue);
  ...
});

Ref