Tests with Jest and React Testing Library (not Enzyme)
Mock Service Worker
remixed official docs and best practices found in various blogs.
hoping to be a simple hello world example for reference.
Key Points Summary
useReducer is similar to useState but for complex state
move logics from view to custom hooks and reducer if needed
use the latest tools (RTL, MSW) for readable test
Setup
# https://github.com/facebook/create-react-app
npx create-react-app todo-ts --template typescript
cd todo-ts
# https://material-ui.com/getting-started/installation/# https://material-ui.com/guides/typescript/
npm install @material-ui/core @material-ui/icons @material-ui/lab
# add Roboto Font to public/index.html in the line before manifest
npm install axios
npm install json-server msw --save-dev
Test and Run
# run backend server (note: waitFor default timeout = 1000ms)
npx json-server --delay 500 db.json
# run app
PORT=4000 BROWSER=none npm start
open http://localhost:4000
# run test
npm test# run test only one file
npm test -- App.test.tsx
# test with coverage
npm test -- --coverage
open coverage/lcov-report/index.html
# https://facebook.github.io/create-react-app/docs/running-tests# build for production
npm run build
# https://facebook.github.io/create-react-app/docs/deployment
Backend Json Server
Json Server is a simple backend server for development
# start
npx json-server db.json
# http://localhost:3000/db# http://localhost:3000/todo# http://localhost:3000/todo/1# todo by curl# create (id is auto increment)
curl -X POST -H 'Content-Type: application/json' \
--data-binary '{"title": "Foo", "done": false}' \
--dump-header /dev/stdout \
http://localhost:3000/todo
# update
curl -X PUT -H 'Content-Type: application/json' \
--data-binary '{"id": 3, "title": "Foo", "done": true}' \
--dump-header /dev/stdout \
http://localhost:3000/todo/3
# delete
curl -X DELETE \
--dump-header /dev/stdout \
http://localhost:3000/todo/3