Unit Testing
When creating or updating a component, it is expected that you add or update the relevant unit test(s) for the component. Jest and React Testing Library are the main libraries that are used for testing components in toynet-react
. More information about these libraries can be found at the repsective links.
Below is a brief guide on how to do unit testing:
Test user behavior when testing a component. This means that you do not need to test the inner state of a component. For example, in a counter component, you would want to test clicking the button, and then expect that the correct value is displayed. This is in contrast to testing the internal state of the component. (See below example).
If the component renders data from an API make sure to mock out the API return call and ensure that the date gets rendered. Checkout mocking modules in Jest's documentation to see how to do this.
Folder and File Structure
Unit tests should live close the files that they are testing in a __tests__
subdirectory.
Writing a Unit Test
A unit test file must follow the filename patter of {filename}.test.(ts|tsx)
and be in a __tests__
subdirectory that lives right next to the component that you are testing.
When writing a unit test it should include a top level describe
block that describes the component being tested. Within that block, there should be one or more it
blocks that describe the behavior being tested for that component.
How to Run the Unit Tests
The unit test can be run by running the command npm run test
. This will run all the tests that have not been ran and bring up an interactive console that can be used to run only failed tests, run all of the tests, or filter test files and names to run a specific test or test suite. To get to this, after running npm run test
press the w
key.
Troubleshooting
It keeps saying that my snapshots are failing.
If it says that there are snapshots that are failing, you can press the i
key to interactively update snapshots and then u
to update the snapshot. If you know that you are updating the DOM layout of a component you can run npm run test -- -u
to update all snapshots.
Last updated