|
| 1 | +import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; |
| 2 | +import { render, screen, fireEvent, waitForElementToBeRemoved } from '@testing-library/angular'; |
| 3 | + |
| 4 | +import { DialogComponent, DialogContentComponent, DialogContentComponentModule } from './15-dialog.component'; |
| 5 | + |
| 6 | +test('dialog closes', async () => { |
| 7 | + const closeFn = jest.fn(); |
| 8 | + await render(DialogContentComponent, { |
| 9 | + imports: [MatDialogModule], |
| 10 | + providers: [ |
| 11 | + { |
| 12 | + provide: MatDialogRef, |
| 13 | + useValue: { |
| 14 | + close: closeFn, |
| 15 | + }, |
| 16 | + }, |
| 17 | + ], |
| 18 | + }); |
| 19 | + |
| 20 | + const cancelButton = await screen.findByRole('button', { name: /cancel/i }); |
| 21 | + fireEvent.click(cancelButton); |
| 22 | + |
| 23 | + expect(closeFn).toHaveBeenCalledTimes(1); |
| 24 | +}); |
| 25 | + |
| 26 | +test('opens and closes the dialog with buttons', async () => { |
| 27 | + await render(DialogComponent, { |
| 28 | + imports: [MatDialogModule, DialogContentComponentModule], |
| 29 | + }); |
| 30 | + |
| 31 | + const openDialogButton = await screen.findByRole('button', { name: /open dialog/i }); |
| 32 | + fireEvent.click(openDialogButton); |
| 33 | + |
| 34 | + await screen.findByRole('dialog'); |
| 35 | + await screen.findByRole('heading', { name: /dialog title/i }); |
| 36 | + |
| 37 | + const cancelButton = await screen.findByRole('button', { name: /cancel/i }); |
| 38 | + fireEvent.click(cancelButton); |
| 39 | + |
| 40 | + await waitForElementToBeRemoved(() => screen.getByRole('dialog')); |
| 41 | + |
| 42 | + const dialogTitle = screen.queryByRole('heading', { name: /dialog title/i }); |
| 43 | + expect(dialogTitle).not.toBeInTheDocument(); |
| 44 | +}); |
| 45 | + |
| 46 | +test('closes the dialog via the backdrop', async () => { |
| 47 | + await render(DialogComponent, { |
| 48 | + imports: [MatDialogModule, DialogContentComponentModule], |
| 49 | + }); |
| 50 | + |
| 51 | + const openDialogButton = await screen.findByRole('button', { name: /open dialog/i }); |
| 52 | + fireEvent.click(openDialogButton); |
| 53 | + |
| 54 | + await screen.findByRole('dialog'); |
| 55 | + await screen.findByRole('heading', { name: /dialog title/i }); |
| 56 | + |
| 57 | + fireEvent.click(document.querySelector('.cdk-overlay-backdrop')); |
| 58 | + |
| 59 | + await waitForElementToBeRemoved(() => screen.getByRole('dialog')); |
| 60 | + |
| 61 | + const dialogTitle = screen.queryByRole('heading', { name: /dialog title/i }); |
| 62 | + expect(dialogTitle).not.toBeInTheDocument(); |
| 63 | +}); |
0 commit comments