首页 > 解决方案 > 为什么在 Angular 单元测试中使用 overrideProvider 或 overrideComponent 来更改提供者依赖值?

问题描述

我有几个使用依赖属性的不同值的单元测试,我阅读了有关 overrideProvider 和 overrideComponent 的信息,但我不认为在这种情况下,当我可以直接更改值而不进行覆盖时它们会很有用。

例如,在下一个片段中,我只是为每个测试重新分配依赖项中的一个属性。

describe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  let testServiceMock: Partial<TestService>;

  beforeEach(() => {
    testServiceMock = {
      someArray: [1, 2, 3]
    };
    TestBed.configureTestingModule({
      declarations: [TestComponent],
      providers: [{ provide: TestService, useValue: testServiceMock }]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  });

  it('should be true when someArray length is bigger than 1', () => {
    fixture.detectChanges();
    expect(component.show).toBeTruthy();
  });

  it('should be false when someArray is null', () => {
    testServiceMock.someArray = null;
    fixture.detectChanges();
    expect(component.show).toBeFalsy();
  });
});

这是一个堆栈闪电战以获取更多信息。 https://stackblitz.com/edit/unit-test-ng-10-natudb?file=src%2Fapp%2Ftest%2Ftest.component.spec.ts

标签: angularunit-testing

解决方案


推荐阅读