Recently, I contributed an Angular CLI example for Jest Preview in collaboration with its creator, Hung Viet Nguyen.
Jest Preview
Jest Preview is a visual debugger for Jest component tests. It runs a preview server and either displays the rendered DOM of a failed test when the autoPreview
option is set or the test we explicitly mark for debugging using the debug
function, for example:
// counter.component.spec.ts
import { render, screen } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
import preview from 'jest-preview';
import { CounterComponent } from './counter.component';
import './counter.component.css';
describe(CounterComponent.name, () => {
it('initially has a zero count', async () => {
const user = userEvent.setup();
await render(CounterComponent);
// Open http://localhost:3336 to see preview
// Require to run `jest-preview` server before
preview.debug(); // π
expect(await screen.findByTestId('count')).toContainHTML('0');
});
});
Angular CLI integration
The Angular CLI guide for Jest Preview refers to the common installation and usage instructions while describing Angular-specific configuration and usage instructions.
While there is room for improvement, we documented workarounds in the guide. Jest Preview is not currently able to automatically transform styleUrls
in component tests, support inline component styles, or automatically import application-wide stylesheets. Because of this, we have to add stylesheet import statements in our tests to match the external stylesheet used by the component-under-test.
For example, say we have this counter component:
// counter.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
styleUrls: ['./counter.component.css'], // π
template: `
<button type="button" (click)="onCount()">
The count is:
<div data-testid="count">{{ count }}</div>
</button>
`,
})
export class CounterComponent {
count = 0;
onCount(): void {
this.count += 1;
}
}
We would have to add an import statement for ./counter.component.css
in our component test:
// counter.component.spec.ts
import { render, screen } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
import preview from 'jest-preview';
import { CounterComponent } from './counter.component';
import './counter.component.css'; // π
describe(CounterComponent.name, () => {
it('displays multiple counts', async () => {
const user = userEvent.setup();
await render(CounterComponent);
await user.click(await screen.findByRole('button'));
await user.click(await screen.findByRole('button'));
// Open http://localhost:3336 to see preview
// Require to run `jest-preview` server before
preview.debug();
expect(await screen.findByTestId('count')).toContainHTML('2');
});
});
Top comments (0)