簡體   English   中英

覆蓋特定測試的 TestBed 提供程序

[英]Override a TestBed Provider for specific test

我有一個組件,它有兩個依賴項:一個是在 angular 中全局定義的LOCALE_ID ,另一個是語言,在組件中定義為{ provide: LANGUAGE_TOKEN, useValue: navigator.language }

對於測試,我都在 TestBed 中為所有測試覆蓋它們,因此測試不會從 Chrome 瀏覽器中注入任何東西來進行業力測試,並且測試不會根據測試環境產生不同的結果:

TestBed.configureTestingModule({
  declarations: [
    MyComponent, RouterStubComponent,
  ],
  imports: [
    MatToolbarModule, RouterTestingModule, MatIconModule, MatButtonModule,
  ],
  providers: [
    {provide: LOCALE_ID, useValue: 'en-US' },
  ]
}).compileComponents();

TestBed.overrideProvider(LOCATION_TOKEN, {useValue: locationStub});
TestBed.overrideProvider(LANGUAGE_TOKEN, {useValue: 'en-US' });

現在我在組件中有一些依賴於語言環境和瀏覽器語言的邏輯,所以我需要模擬它們。 Mocking LANGUAGE_TOKEN非常簡單,幾乎沒有不便:

 it('should redirect to spanish when in spanish browser', () => {
    TestBed.overrideProvider(LANGUAGE_TOKEN, {useValue: 'es'});
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    expect(hrefSpy.calls.count()).toBe(1);
    expect(hrefSpy.calls.argsFor(0)[0]).toEqual(environment.spanUrl);
  });

但是,使用相同的代碼覆蓋LOCALE_ID不起作用。

  it('should ...', () => {
    TestBed.overrideProvider(LOCALE_ID, {useValue: 'es-ES'});
    console.log(TestBed.get(LOCALE_ID)); // en-US!!!!
    fixture = TestBed.createComponent(MamanComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    expect(hrefSpy.calls.count()).toBe(1); //FAIL
    expect(hrefSpy.calls.argsFor(0)[0]).toEqual(environment.engUrl);//FAIL
  });

我也無法在這個問題中找到有效的答案。

這是因為一旦您調用compileComponents ,提供程序就會被凍結並且不會被覆蓋。

providers中刪除LOCALE_ID以使其值不被凍結。 (但請確保在創建組件實例之前使用overrideProviders提供它):

TestBed.configureTestingModule({
  declarations: [
    MyComponent, RouterStubComponent,
  ],
  imports: [
    MatToolbarModule, RouterTestingModule, MatIconModule, MatButtonModule,
  ],
  providers: [
    --> remove 
  ]
}).compileComponents();

TestBed.overrideProvider(LOCALE_ID, {useValue: 'es-ES'});
//Add it before creating component, to have a default value in each test, add it in a beforeEach block.

或者您可以在每個測試中創建組件實例之前調用compileComponents

TestBed.configureTestingModule({
  declarations: [
    MyComponent, RouterStubComponent,
  ],
  imports: [
    MatToolbarModule, RouterTestingModule, MatIconModule, MatButtonModule,
  ],
  providers: [
    {provide: LOCALE_ID, useValue: 'en-US' },
  ]
});
--> remove compileComponents

然后在每次測試中:

it('should ...', () => {
    TestBed.overrideProvider(LOCALE_ID, {useValue: 'es-ES'});
    // Add here
    TestBed.compileComponents();
    fixture = TestBed.createComponent(MamanComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    expect(hrefSpy.calls.count()).toBe(1); //FAIL
    expect(hrefSpy.calls.argsFor(0)[0]).toEqual(environment.engUrl);//FAIL
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM