An example of the testing approach I've taken with vite, @web/test-runner, storybook, and jest libraries
This project is an example of the approach I take to test my frontend application.
It uses a combination of the following libraries:
expect
assertionsTo see this in action, clone the repo and then fire up the storybook with:
npm install
npm run storybook
to run the tests, either use
npm test
Which will run the unit tests (so far only one here) in three different headless browsers, or
npm test:watch
to start up the tests in watch mode in headless chrome alone.
The main testing approach is to create storybook stories for components and even pages, and then test against those stories. This has a few benefits:
Furthermore, I can use the play
function of storybook 6.4, and execute user interactions directly in the story, preventing the need for a separate test file in some cases. The next version of storybook will include a test runner to execute the play functions as tests, but for now chromatic snapshots fit that need for me, since they will fail if a play
function fails. See src/screens/animals/AnimalsPage.stories.tsx
for an example of a story with a test built in to the play
function.
I use MirageJS to mock out network calls, which allows me to easily create different kinds of stories for each component, simply by adjusting the state of the mock api server or what it returns. See src/components/animal-list/AnimalList.stories.tsx
for an example of creating empty, loading, error, and populated stories by changing the api mocks.
Unfortunately jest was not built to run in a browser and their ESM support is still being worked on, so it's not a great fit for vite projects yet. However, there are some useful parts of jest that are published separately, which we can take advantage of.
expect
library published by jest is not directly browser-compatible, but storybook has released a version of it that is, which is what I'm using here.jest.fn()
and jest.spyOn()
. For an example test using jest-mock, see src/components/animal-form/AnimalForm.test.tsx
.src/api/fetch.test.ts
for an example.expect
when interacting with a dom.