[TOC]
# 介紹
**測試** 是應用生產過程中不可缺少的一個環節,開發人員在編碼時總有考慮不周全或者出錯的情況,而測試則是通過對比實際結果與預期結果來找出問題和缺陷,從而確保軟件的質量。
對于**任何想要高質量的項目來說,測試和調試都是非常重要的**。不幸的是,許多開發人員并不關心測試(單元測試),因為他們認為這將降低開發的速度,并且有些開發人員將其留到項目的末尾。根據我個人的經驗,我可以說從項目開始進行測試將節省您的時間,因為到最后,您需要修復的bug會更少。
React 使用 Jest 測試 components, containers, actions, 和 reducers。
在下面的章節中,我們還將學習如何調試 React/Redux 應用程序。
# React組件的測試
測試React組件我們采用 Enzyme 工具庫,它提供3種組件渲染方式:
1. **shallow**:不會渲染子組件(推薦使用這種測試,子組件再使用這種測試)
2. **mount**: 渲染子組件,同時包含生命周期函數如 `componentDidMount`
3. **render**: 渲染子組件,但不會包含生命周期,同時可用的API也會減少比如 `setState()`
一般情況下用 `shallow` 和 `mount` 的情況比較多。
# redux 測試
# 測試 redux-saga
# 測試 hooks
# 工具
對于一些測試情況,可能會用到的工具
[redux-mock-store](https://codeday.me/bug/20190321/796372.html)
[nock](https://github.com/nock/nock) -- HTTP server mocking and expectations library for Node.js
[Sinon](https://sinonjs.org/) -- Standalone and test framework agnostic JavaScript test spies, stubs and mocks
# 示例
[deepfunc/react-test-demo](https://github.com/deepfunc/react-test-demo)
[testing-library](https://testing-library.com/)
[Testing React with Enzyme and Jest](https://javascriptplayground.com/testing-react-enzyme-jest/)
[kentcdodds‘s Blog](https://kentcdodds.com/)