skills of writing unit testing for react
Author: markzzw | Date: 2023-12-30
code repo: https://github.com/zhangzewei/Skills-of-writing-unit-test-for-react-demo-code
After writing some unit tests for react project, I summarised some skills of writing unit tests for react.
Tech stack
This is the tech stack of it, we need to prepare it.
vite - react (react 18)
vitest (1.0.4)
@testing-library/react (14.1.2)
Setup test env
Before we start it, we need to set up the test env.
1. install dependencies
npm install vitest
npm install @testing-library/jest-dom
npm install @testing-library/react2. Add configuration in vite-config
3. Create ./src/test/setup.ts
./src/test/setup.ts4. Set script in package.json
Then we can run the script npm run test in the console.
Test render with different props
In this kind of Component, use render() to render different props, and test the component render if is correct.
Test with HTML_EVENTs
When talking about unit tests, we can't avoid the event test, there are two ways to write it, and we need to use act(() => {}) to wrap the event step.
Trigger event directly
This way is always used to test the click events.
Also if Component needs to pass the function through the props, we can test the function if be called, we can use vi.fn() as the mock spy.
Trigger event by using fireEvent provided by the @testing-library/react
fireEvent provided by the @testing-library/reactThis way is mostly used on input event, scroll event, and some events that need to pass/get value.
If your event function has been wrapped by a setTimeOut function like debounce/throttle, then we need to use async/await and waitFor(() => {}) to help us.
Test hook function
Usually, we will write hooks to help us, so we need to test the hook function too, for hook we need to use renderHook() to help us.
renderHook also is provided by @testing-library/react.
Here is a hook function that I write to get detail data, I use the useEffect to update the detail when I change the dependencies, and I use a loading status from the redux store.
This is a typical fetch data hook, let's test it.
useDetailData.ts
useDetailData.test.tsx
First I write a function to mock a fetch function, because we use the Promise the setTtimeOut function, so we need to use async/await.
As I noticed I use a loading status from redux store, so we also need to mock the redux, so I write the ReduxProviderWrapper.
All right, all the setups are ready, now we use the renderHook() to render our hook, the first param of the renderHook is a function that we can set the props, the props are what the hook function params have been, and we can set initialProps in the second param of the renderHook, so that we can use the rerender(newProps) returned by renderHook to change dependencies, and test the result if is correct, and don't forget to set the wrapper ReduxProviderWrapper in the second param of renderHook when we use the redux.
Now we finished most tests of this hook, but if we need to get our coverage to be 100% we still need to test one if we don't set any dependency, we just need to add one more test case.
Then we can get our satisfactory test coverage report.
Test coverage
useDetailData.ts
100
100
100
100
Test with react-router
If we use the react-router, we also need to provide the router context when we test it.
How to provide router context? Using MemoryRouter which is provided by react-router.
For example, I test a hook using the router hook useLocation(), so I need to provide a router context as a wrapper for renderHook().
useQuery hook
useQuery.test.tsx
Through the initialEntries props to mock the route currently used.
Test with the mock function
Sometimes we should mock some functions to return the result as we need so that we can test the function's behavior if is correct.
For this vitest provide the vi.mock('path/of/import/function') & vi.mocked().mockReturnValue().
usePosts.ts
In this hook, the request function getPost is a fetch function imported from the request file, but when we test it we don't want to get the real data back, we need to use mock data so that we can control the expct statement.
usePost.test.ts
First use vi.mock() to mock the import function, this should do outside the describe, this is a requirement from vitest.
Then use vi.mocked(importFunction).mockReturnValue(mockValue) to mock the function and its return value.
Also should use async/await & waitFor because of the promise fetching.
Summary
At the end of this document, we have learned so many skills of writing unit tests for react, I hope those skills can help you to write unit tests easier.
Thx for reading.
Last updated