1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Angular testing: correct way to detectChanges when mocking a service that is used on ngOnInit

Discussão em 'Angular' iniciado por Lucas Pottersky, Outubro 10, 2024 às 12:52.

  1. When I uncomment the first call to fixture.detectChanges(), the test does not work as expected.

    The IA told me to:

    1. Set up the mock before creating the component: This ensures that the component is created with the mocked service in place.
    2. Trigger change detection after setting up the mock: This forces the component to re-render based on the updated mock data.

    My questions are:

    1. Why is that?
    2. Is there a way to force the change detection, regardless of input change?
    3. What if I want to call detectChanges() on beforeEach()? Then I can't setup mocks inside specific tests?
    4. Is it a good practice to call createComponent inside each specific test (it) instead?

    OBS: I am using Angular 11.

    test code:

    import { ComponentFixture, TestBed } from '@angular/core/testing';

    import { MyComponent } from './my.component';
    import { SomeService } from '../services/some.service';

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

    beforeEach(async () => {
    const spy = jasmine.createSpyObj('SomeService', ['aMethod']);

    await TestBed.configureTestingModule({
    declarations: [ MyComponent ],
    providers: [
    { provide: SomeService, useValue: spy }
    ]
    })
    .compileComponents();
    });

    it('should show another mock', () => {
    // This code was moved from beforeEach()
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    compiled = fixture.nativeElement;

    // *** MOCK VALUE ISN'T PICKED IF THIS IS UNCOMMENTED ***
    fixture.detectChanges();

    const mock: jasmine.SpyObj<SomeService> = TestBed.inject(SomeService) as jasmine.SpyObj<SomeService>;;
    mock.aMethod.and.returnValue('MOCKED VALUE');

    fixture.detectChanges();

    expect(compiled.querySelector('p').innerHTML).toContain('MOCKED VALUE');
    });
    });


    component code:

    import { Component, OnInit } from '@angular/core';
    import { SomeService } from '../services/some.service';

    @Component({
    selector: 'app-my',
    template: `
    <p>
    myPropIs = {{ propThatReadsFromService }}
    </p>
    `,
    styles: [
    ]
    })
    export class MyComponent implements OnInit {
    propThatReadsFromService: string = 'not set yet';
    constructor(private someService: SomeService) { }

    ngOnInit(): void {
    this.propThatReadsFromService = this.someService.aMethod() || 'did not pick value from service';
    }
    }

    Continue reading...

Compartilhe esta Página