Examples
Read about best practices, or follow the guided example
Angular Testing Library can be used with standalone components and also with Angular components that uses Modules. The example below shows how to test a standalone component, but the same principles apply to Angular components that uses Modules. In fact, there should be no difference in how you test both types of components, only the setup might be different.
counter.component.ts
@Component({
selector: 'app-counter',
template: `
<span>{{ hello() }}</span>
<button (click)="decrement()">-</button>
<span>Current Count: {{ counter() }}</span>
<button (click)="increment()">+</button>
`,
})
export class CounterComponent {
counter = model(0)
hello = input('Hi', {alias: 'greeting'})
increment() {
this.counter.set(this.counter() + 1)
}
decrement() {
this.counter.set(this.counter() - 1)
}
}
counter.component.spec.ts
import {render, screen, fireEvent, aliasedInput} from '@testing-library/angular'
import {CounterComponent} from './counter.component'
describe('Counter', () => {
it('should render counter', async () => {
await render(CounterComponent, {
inputs: {
counter: 5,
// aliases need to be specified using aliasedInput
...aliasedInput('greeting', 'Hello Alias!'),
},
})
expect(screen.getByText('Current Count: 5')).toBeVisible()
expect(screen.getByText('Hello Alias!')).toBeVisible()
})
it('should increment the counter on click', async () => {
await render(CounterComponent, {inputs: {counter: 5}})
const incrementButton = screen.getByRole('button', {name: '+'})
fireEvent.click(incrementButton)
expect(screen.getByText('Current Count: 6')).toBeVisible()
})
})
More examples
More examples can be found in the GitHub project. These examples include:
input
andoutput
properties- Forms
- Integration injected services
- And more
If you're looking for an example that isn't on the list, please feel free to create a new issue.