|
| 1 | +import { Component } from '@angular/core'; |
| 2 | +import { Router } from '@angular/router'; |
| 3 | +import { render, screen, waitForElementToBeRemoved } from '@testing-library/angular'; |
| 4 | +import userEvent from '@testing-library/user-event'; |
| 5 | + |
| 6 | +it('test click event with router.navigate', async () => { |
| 7 | + const user = userEvent.setup(); |
| 8 | + await render(`<router-outlet></router-outlet>`, { |
| 9 | + routes: [ |
| 10 | + { |
| 11 | + path: '', |
| 12 | + component: LoginComponent, |
| 13 | + }, |
| 14 | + { |
| 15 | + path: 'logged-in', |
| 16 | + component: LoggedInComponent, |
| 17 | + }, |
| 18 | + ], |
| 19 | + }); |
| 20 | + |
| 21 | + expect(await screen.findByRole('heading', { name: 'Login' })).toBeVisible(); |
| 22 | + expect(screen.getByRole('button', { name: 'submit' })).toBeInTheDocument(); |
| 23 | + |
| 24 | + const email = screen.getByRole('textbox', { name: 'email' }); |
| 25 | + const password = screen.getByLabelText('password'); |
| 26 | + |
| 27 | + await user.type(email, '[email protected]'); |
| 28 | + await user.type(password, 'with_valid_password'); |
| 29 | + |
| 30 | + expect(screen.getByRole('button', { name: 'submit' })).toBeEnabled(); |
| 31 | + |
| 32 | + await user.click(screen.getByRole('button', { name: 'submit' })); |
| 33 | + |
| 34 | + await waitForElementToBeRemoved(() => screen.queryByRole('heading', { name: 'Login' })); |
| 35 | + |
| 36 | + expect(await screen.findByRole('heading', { name: 'Logged In' })).toBeVisible(); |
| 37 | +}); |
| 38 | + |
| 39 | +@Component({ |
| 40 | + template: ` |
| 41 | + <h1>Login</h1> |
| 42 | + <button type="submit" (click)="onSubmit()">submit</button> |
| 43 | + <input type="email" aria-label="email" /> |
| 44 | + <input type="password" aria-label="password" /> |
| 45 | + `, |
| 46 | +}) |
| 47 | +class LoginComponent { |
| 48 | + constructor(private router: Router) {} |
| 49 | + onSubmit(): void { |
| 50 | + this.router.navigate(['logged-in']); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +@Component({ |
| 55 | + template: ` <h1>Logged In</h1> `, |
| 56 | +}) |
| 57 | +class LoggedInComponent {} |
0 commit comments