vitest is a new unit testing tool that is fast, supports esm by default, is compatible with the jest api, and can be considered a better jest. by default, it supports the following features being used
- very fast
- esm support
- ts support
- Compatible with jest api
- support for vite
- support for multiple frameworks react/vue
vitest internally depends on vite, but it is not necessary to install vite.
Well, actually vitest is really zero configuration and supports ts/esm/tsx, but if you want more features, you can indeed create vitest.config.ts file or add configuration directly to vite.config.ts.
Basically, it is similar to jest in that you create a
__tests__ folder in the same directory as the file you want to test, and then create a file in it with a file name ending in .test.ts and the following contents.
pnpm vitest hello.test.ts to run the unit tests in monitor mode.
You can use
describe groups if you have multiple tests.
-t parameter can also be used to specify the test to be executed, for example
It is also possible to use
it.only/descrive.only to specify the tests to be executed.
Also some hook functions like beforeEach/afterEach are supported.
For example, a test directory is created by default.
vitest has chaijs built in by default as an assertion library and is compatible with jest’s assertion api.
Most interestingly, it supports some assertions very concisely, such as asserting some common values.
Or compare the values.
web api polyfill
Usually some dom api are included in web projects for testing, such as localStorage/indexedDB etc.
The dom-related api mock can be implemented with
happy-dom, which is a simple dom implementation that runs in node and has less api than jsdom, but is faster.
nodejs@18 supports fetch requests and no longer requires polyfill.
Unfortunately hyppy-dom doesn’t implement indexedDB, so we need to use
fake-indexeddb to do the polyfill.
This doesn’t require much configuration, just import it in the test file.
- vitest has a vscode plugin, but monorepo is not yet supported, so it is recommended not to use it
- vitest is based on vite, and variables like
__dirname/__filenameare available in tests, but not actually available in nodejs esm
- vitest has overlap with the node:test api, especially it/describe, so be careful not to misquote it