Skip to content

autoDetectChanges not automatically detect changes as a "real" running component would do #492

Closed
@vladtheimpala

Description

@vladtheimpala

Issue
Reading the documentation of render method, autoDetectChanges option is supposed to take care of the change detection for us.

automatically detect changes as a "real" running component would do

But it seems it is not the case with Observable and async pipe at least we have to call detectChanges manually.

Example
Simple user component displaying username resolved from a UserService acting as a store
Testing the username change coming from the service is correctly rendered by the component

component under test :

@Component({
  selector: 'app-user',
  standalone: true,
  template: `<h1>{{ username$ | async }}</h1>`,
})
export class UserComponent {
  readonly username$: Observable<string> = inject(UserService).getName();
}

test :

describe('UserComponent', () => {
  it('should display username', async () => {

    // stubbed user service using a Subject
    const user = new BehaviorSubject({ name: 'username 1' });
    const userServiceStub: Partial<UserService> = {
      getName: () => user.asObservable().pipe(map(user => user.name))
    };

    // render the component with injection of the stubbed service
    const { detectChanges } = await render(UserComponent, {
      componentProviders: [
        {
          provide: UserService,
          useValue: userServiceStub
        }
      ]
    });

    // assert first username emitted is rendered
    expect(await screen.findByRole('heading')).toHaveTextContent('username 1');

    // emitting a second username
    user.next({ name: 'username 2' });

    detectChanges(); // => is required to make my test pass, would not be required in a "real" running component <= 

    // assert the second username is rendered
    expect(await screen.findByRole('heading')).toHaveTextContent('username 2');
  });
});
Screenshot 2024-10-07 at 19 06 22

Expected behavior
As written in the documentation, autoDetectChanges should handle changes detection as a real component would do

  • Ideally we want to avoid manually calling detectChanges() method when change detection would naturally occurs in a real browser context
    • ChangeDetectionStrategy of the component should be taken in account
  • Else document when autoDetectChanges really run change detection for us

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions