Skip to content

detectChanges needed if using user-event#click #491

Closed
@lebbers

Description

@lebbers

In a Karma + jasmine setup, I need to explicitly call detectChanges after I've used the @testing-library/user-event#click event on a button that routes to another component. Is that how it should behave or am I doing something wrong here?

In angular-testing-library/apps/example-app-karma/src/app/examples/login-form.spec.ts i've added the following test. If the detectChanges call is removed the test fails.

it('test click event with router.navigate', async () => {
  const user = userEvent.setup();
  const { detectChanges } = await render(`<router-outlet></router-outlet>`, {
    routes: [
      {
        path: '',
        component: LoginComponent,
      },
      {
        path: 'logged-in',
        component: LoggedInComponent,
      },
    ],
  });

  expect(screen.getByRole('heading', { name: 'Login' })).toBeVisible();
  expect(screen.getByRole('button', { name: 'submit' })).toBeInTheDocument();

  const email = screen.getByRole('textbox', { name: 'email' });
  const password = screen.getByLabelText('password');

  await user.type(email, 'user@example.com');
  await user.type(password, 'with_valid_password');

  expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled();

  await user.click(screen.getByRole('button', { name: 'submit' }));
  detectChanges(); // <-- Removing this will fail the test

  await waitFor(() => expect(screen.queryByRole('heading', { name: 'Login' })).not.toBeInTheDocument());

  expect(await screen.findByRole('heading', { name: 'Logged In' })).toBeVisible();
});

@Component({ /*...*/ });
class LoginComponent {
  // ...
  constructor(private fb: FormBuilder, private router: Router) {}
  // ...
  onSubmit(_fg: FormGroup): void {
    this.router.navigate(['logged-in']);
  }
}

@Component({
  selector: 'app-logged-in',
  standalone: true,
  template: ` <h1>Logged In</h1> `,
})
class LoggedInComponent {}

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