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:
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.
{
"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.