本文轉載自:衆成翻譯
譯者:iOSDevLog
連接:http://www.zcfy.cc/article/3804
原文:https://www.fullstackreact.com/30-days-of-react/day-24/css
咱們先看一下咱們應用的一個特徵,並考慮邊緣案例的位置以及咱們假設將會發生的狀況node
.讓咱們從Timeline
組件開始, 由於它是咱們當前應用中最複雜的。react
Timeline
組件 顯示 一個具備動態標題的標題的狀態列表。咱們要測試咱們的組件中的任何動態邏輯。咱們必須從測試開始的最簡單的邏輯是圍繞Timeline
的動態標題。npm
咱們喜歡開始測試, 列出咱們對一個組件的假設, 以及在什麼狀況下這些假設是真實的。例如, 咱們能夠對Timeline
組件進行假設的列表可能包括如下內容:app
在任何狀況下, Timeline
將包含 一個有.notificationsFrame
類的<div />
。函數
在任何狀況下, 咱們能夠假設會有一個標題測試
在任何狀況下, 咱們假設搜索按鈕將開始隱藏spa
有至少四狀態更新的列表翻譯
這些 假設 將轉化爲咱們的測試。code
讓咱們打開src/components/Timeline/__tests__/Timeline-test.js
文件。咱們在這個文件中留下了一些虛擬測試, 因此讓咱們清除這些, 並開始一個新的描述塊:
describe('Timeline', () => { // Tests go here })
對於咱們編寫的針對React每一個測試的咱們都但願測試文件導入React。咱們還要引入React測試實用程序:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; describe('Timeline', () => { // Tests go here })
因爲咱們在這裏測試Timeline
組件, 所以咱們還但願將其引入到咱們的工做區中:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { // Tests go here })
讓咱們寫第一個測試。咱們的第一個假設是很是簡單的測試。咱們正在測試以確保元素被包裝在.notificationsFrame
類中。在咱們編寫的每一個測試中, 咱們都須要將應用呈如今工做測試文檔中。react-addons-test-utils
庫提供了一個函數來執行這個叫作renderIntoDocument()
:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { it('wraps content in a div with .notificationsFrame class', () => { const wrapper = TestUtils.renderIntoDocument(<Timeline />); }); })
若是咱們運行這個測試 (儘管咱們尚未設定任何指望), 咱們會發現測試代碼有問題。React認爲咱們正在嘗試呈現一個未定義的組件:
讓咱們在 DOM 中使用另外一個稱爲findRenderedDOMComponentWithClass()
的TestUtils
函數來找到咱們指望的元素。
findRenderedDOMComponentWithClass()
函數接受 兩個 參數。第一個是渲染樹 (咱們的wrapper
對象), 第二個是咱們但願它查找的 css 類名:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { it('wraps content in a div with .notificationsFrame class', () => { const wrapper = TestUtils.renderIntoDocument(<Timeline />); const node = TestUtils .findRenderedDOMComponentWithClass(wrapper, 'notificationsFrame'); }); })
這樣, 咱們的測試就會經過 (相信與否)。TestUtils 設置了一個指望, 即它能夠在.notificationsFrame
類中找到該組件。若是它沒有找到一個, 它將拋出一個錯誤, 咱們的測試將失敗。
做爲提醒, 咱們可使用 npm test
命令或yarn test
命令來運行測試。咱們將使用yarn test
命令, 由於咱們正在測試一個組件:
yarn test
經過咱們的一次測試, 咱們確認了咱們的測試設置正在運行。
不幸的是, TestUtils
的界面有點複雜和低級。enzyme
庫是TestUtils
的封裝, 提供一個更容易和 高級 的界面, 斷言針對的React組件在測試。明天咱們將詳細討論酶。
今天的工做很好, 明天見!