-
Notifications
You must be signed in to change notification settings - Fork 93
Closed
Description
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');
});
});
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 contextChangeDetectionStrategyof the component should be taken in account
- Else document when
autoDetectChangesreally run change detection for us
Metadata
Metadata
Assignees
Labels
No labels