|
| 1 | +import { AsyncPipe } from '@angular/common'; |
| 2 | +import { Component, inject, Injectable } from '@angular/core'; |
| 3 | +import { render, screen, waitFor } from '../../src/public_api'; |
| 4 | +import { Observable, BehaviorSubject, map } from 'rxjs'; |
| 5 | + |
| 6 | +test('displays username', async () => { |
| 7 | + // stubbed user service using a Subject |
| 8 | + const user = new BehaviorSubject({ name: 'username 1' }); |
| 9 | + const userServiceStub: Partial<UserService> = { |
| 10 | + getName: () => user.asObservable().pipe(map((u) => u.name)), |
| 11 | + }; |
| 12 | + |
| 13 | + // render the component with injection of the stubbed service |
| 14 | + await render(UserComponent, { |
| 15 | + componentProviders: [ |
| 16 | + { |
| 17 | + provide: UserService, |
| 18 | + useValue: userServiceStub, |
| 19 | + }, |
| 20 | + ], |
| 21 | + }); |
| 22 | + |
| 23 | + // assert first username emitted is rendered |
| 24 | + expect(await screen.findByRole('heading')).toHaveTextContent('username 1'); |
| 25 | + |
| 26 | + // emitting a second username |
| 27 | + user.next({ name: 'username 2' }); |
| 28 | + |
| 29 | + // assert the second username is rendered |
| 30 | + await waitFor(() => expect(screen.getByRole('heading')).toHaveTextContent('username 2')); |
| 31 | +}); |
| 32 | + |
| 33 | +@Component({ |
| 34 | + selector: 'atl-user', |
| 35 | + standalone: true, |
| 36 | + template: `<h1>{{ username$ | async }}</h1>`, |
| 37 | + imports: [AsyncPipe], |
| 38 | +}) |
| 39 | +class UserComponent { |
| 40 | + readonly username$: Observable<string> = inject(UserService).getName(); |
| 41 | +} |
| 42 | + |
| 43 | +@Injectable() |
| 44 | +class UserService { |
| 45 | + getName(): Observable<string> { |
| 46 | + throw new Error('Not implemented'); |
| 47 | + } |
| 48 | +} |
0 commit comments