Angular testing using vitest and testing-library
To test the angular project using vitest and testing-library, first, install the required libraries on devDependencies
- vite
- vitest
- @testing-library/angular
- @testing-library/jest-dom
- jsdom
- jest-preset-angular
- reflect-metadata
- @swc/core
- unplugin-swc
- @types/testing-library__jest-dom
Then we need to create test-setup.ts to initialize the testing environment. Zone js doesn't play well with vitest, so we need to make fake zone js (with empty implementation). Noop zone js implementation is from Younes Jaaidi's github, here.
import './noop-zone'
import 'jest-preset-angular/setup-jest'
import 'reflect-metadata'
import '@testing-library/jest-dom'
Configure vite.config.ts
import { defineConfig } from 'vite'
import swc from 'unplugin-swc'
export default defineConfig(() => {
return {
test: {
environment: 'jsdom',
globals: true,
setupFiles: 'testing/test-setup.ts',
},
plugins: [
swc.vite(),
],
esbuild: false,
}
})
Because we're using globals: true, we need to update tsconfig.ts types for typings
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"types": [
"vitest/globals"
]
}
}
For further reference, you can see vitest documentation here.
Thats it. You can start writing tests. For source code, you can see it on my github repository.