Skip to main content
Frontend tutorial

6.3. More testing (Bonus)

In your own project​

Install the tools for testing:

pnpm add -D vitest happy-dom
  • Vitest writes and runs our tests.
  • happy-dom emulates the browser API, so a test can render a component.

Store tests don't need a browser, but component tests do. We add the test config to vite.config.ts, so the app and the tests share one config:

vite.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

export default defineConfig({
plugins: [react()],
test: {
environment: 'happy-dom',
},
});

Then add the scripts and run pnpm test. It watches your files and runs the tests again on every save.

package.json
{
"scripts": {
"test": "vitest",
"test-coverage": "vitest run --coverage"
}
}

For the tests I wrote for the mobx-example demo, see its Store.test.ts. Its actions have other names (addOne, add100), but the tests follow the same list.

Coverage​

Coverage shows which lines your tests never ran. It needs one more package:

pnpm add -D @vitest/coverage-v8
pnpm test-coverage

A high number doesn't mean the tests check the right things, but a low one tells you where to look. By default the report lists only the files your tests load; to see the others at 0%, add coverage: { include: ['src/**'] } to test.

End-to-end testing​

If we want to test the way users use the application, we can use Playwright. It opens a real browser, clicks the buttons and checks what's on the screen. It's much slower than Vitest, so I'd keep it for the few paths that really matter.

06 / Tests

Three kinds of tests

Three kinds of testsStore tests run in Vitest without a browser and take milliseconds, so most tests are store tests. Component tests add happy-dom, which emulates the browser. End-to-end tests drive a real browser with Playwright; they are slow, so keep them for the paths that matter.StoreVitestno browsermost testsComponentVitestwith happy-domsomeEnd-to-endPlaywrightreal browserkey pathsslower, but closer to the user

The closer a test gets to the user, the slower it runs, so write fewer of them.