Examples
Read about best practices, or follow the guided example
@Component({
selector: 'counter',
template: `
<button (click)="decrement()">-</button>
<span data-testid="count">Current Count: {{ counter }}</span>
<button (click)="increment()">+</button>
`,
})
export class CounterComponent {
@Input() counter = 0
increment() {
this.counter += 1
}
decrement() {
this.counter -= 1
}
}
import {render, screen, fireEvent} from '@testing-library/angular'
import {CounterComponent} from './counter.component.ts'
describe('Counter', () => {
test('should render counter', async () => {
await render(CounterComponent, {
componentProperties: {counter: 5},
})
expect(screen.getByText('Current Count: 5')).toBeInTheDocument()
})
test('should increment the counter on click', async () => {
await render(CounterComponent, {
componentProperties: {counter: 5},
})
fireEvent.click(screen.getByText('+'))
expect(screen.getByText('Current Count: 6')).toBeInTheDocument()
})
})
With Standalone Components
Angular Testing Library can also test your standalone components. In fact, it even becomes easier because you don't have to set up the whole Angular TestBed. This was previously only possible when you used Single Component Angular Modules (SCAMs).
Let's migrate the counter component to a standalone component, and let's take a look at how this affects the test.
@Component({
selector: 'counter',
template: `
<button (click)="decrement()">-</button>
<span data-testid="count">Current Count: {{ counter }}</span>
<button (click)="increment()">+</button>
`,
standalone: true,
})
export class CounterComponent {
@Input() counter = 0
increment() {
this.counter += 1
}
decrement() {
this.counter -= 1
}
}
Just as you would've expected, this doesn't affect the test cases. Writing tests for standalone components remains the same as for "regular" components.
import {render, screen, fireEvent} from '@testing-library/angular'
import {CounterComponent} from './counter.component.ts'
describe('Counter', () => {
test('should render counter', async () => {
await render(CounterComponent, {
componentProperties: {counter: 5},
})
expect(screen.getByText('Current Count: 5')).toBeInTheDocument()
})
test('should increment the counter on click', async () => {
await render(CounterComponent, {
componentProperties: {counter: 5},
})
fireEvent.click(screen.getByText('+'))
expect(screen.getByText('Current Count: 6')).toBeInTheDocument()
})
})
To override the an import of a standalone component for your component test, you
can use the ɵcomponentImports
property.
More examples
More examples can be found in the GitHub project. These examples include:
@Input
and@Output
properties- Forms
- Integration with services
- And more
If you're looking for an example that isn't on the list, please feel free to create a new issue.