给出下面的示例规格测试
beforeEach(function () {
TestBed.configureTestingModule({
providers: [
{ provide: TranslateService, useClass: TranslateServiceMock },
{ provide: StoreService, useClass: StoreServiceMock },
{
provide: GLOBAL_CONFIG_TOKEN,
useValue: { default: true }
}
],
});
let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
});
it('should override provider otherwise what is the point? :)', () => {
let config = TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
expect(config).toEqual({default: false, random: 'damn'});
});
问题是测试失败,因为default始终为true,而random不是config的属性。这意味着在配置测试模块期间config仍具有默认值,并且提供程序尚未被覆盖。
知道为什么吗? overrideProvider方法是否只是用于更新最初在configureTestingModule中传递的moduleRef对象的助手?
似乎在[[TestBed.overrideProvider之前运行TestBed.inject会导致overrideProvider无效的事实。应该在TestBed.inject()之前使用overrideProvider函数。显然,这只是运行configurTestingModule()函数后的帮助方法。因此,上述示例的解决方案是:
beforeEach(function () {
TestBed.configureTestingModule({
providers: [
{ provide: TranslateService, useClass: TranslateServiceMock },
{ provide: StoreService, useClass: StoreServiceMock },
{
provide: GLOBAL_CONFIG_TOKEN,
useValue: { default: true }
}
],
});
});
it('should override provider otherwise what is the point? :)', () => {
TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
expect(config).toEqual({default: false, random: 'damn'});
});
尽管如此,您仍然可以在TestBed.overrideProvider
之前执行此操作。
(getTestBed() as any)._instantiated = false;
(getTestBed() as any)._moduleFactory = undefined;