TestBed.OverrideProvider()如果TestBed.inject()或TestBed.get()(已弃用)在运行之前不起作用

问题描述 投票:0回答:2

给出下面的示例规格测试

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对象的助手?

angular unit-testing karma-jasmine testbed
2个回答
0
投票

似乎在[[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'}); });

0
投票
是的,因为有内置函数可以触发测试模块的编译。如果要在需要重置testBed之后更新该值,则只能通过访问私有属性来执行此操作,因此不建议这样做,最好是在首先创建env然后提取其数据时编写适当的测试。

尽管如此,您仍然可以在TestBed.overrideProvider之前执行此操作。

(getTestBed() as any)._instantiated = false; (getTestBed() as any)._moduleFactory = undefined;

© www.soinside.com 2019 - 2024. All rights reserved.