Why use overrideProvider or overrideComponent in Angular unit test to change the provider...

Discussão em 'Angular' iniciado por ALopez, Março 14, 2025.

  1. ALopez

    ALopez Guest

    I have several unit tests that use different values of a dependency property, I read about overrideProvider and overrideComponent, but I can't think in which case they would be useful when I can just change the value directly without overriding.

    For example in the next snippet I'm just reassigning a property in the dependency for each test.

    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();
    });
    });


    Here is an stackblitz for more information. https://stackblitz.com/edit/unit-test-ng-10-natudb?file=src/app/test/test.component.spec.ts

    Continue reading...

Compartilhe esta Página