使用TypeScript開發React應用(四) - Jest單元測試
繼續前面的文章ofollow,noindex" target="_blank">使用TypeScript開發React應用(三) 介紹了React+TypeScript應用的搭建中如何建立狀態元件
下面繼續分享元件的單元測試
用Jest寫測試
我們對Hello元件有一定的假設。 讓我們重申它們是什麼:
<div>Hello Durban!!!</div>
我們可以使用這些要求為我們的元件編寫一些測試。
但首先,讓我們安裝Enzyme。Enzyme 是React生態系統中的常用工具,可以更輕鬆地編寫元件行為方式的測試。 預設情況下,我們的應用程式包含一個名為jsdom的庫,允許我們模擬DOM並在沒有瀏覽器的情況下測試其執行時行為。 Enzyme類似,但建立在jsdom上,可以更容易地對我們的元件進行某些查詢。
讓我們將其安裝為開發時依賴項。
npm install -D enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer
注意我們安裝了包enzyme
以及@types/enzyme
。 enzyme包是指包含實際執行的JavaScript程式碼的包,而@types/enzyme
是包含宣告檔案(.d.ts檔案)的包,因此TypeScript可以理解如何使用Enzyme。 您可以在此處
瞭解有關@types包的更多資訊。
我們還必須安裝enzyme-adapter-react-16
和react-test-renderer
。 這是enzyme
預期安裝的東西。
在編寫第一個測試之前,我們必須配置Enzyme以使用React 16的介面卡。我們將建立一個名為src/setupTests.ts的檔案,在執行測試時自動載入,程式碼示例如下
import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme.configure({ adapter: new Adapter() });
現在我們已經設定了enzyme,讓我們開始編寫測試! 讓我們建立一個名為src/components/Hello.test.tsx的檔案,與之前的Hello.tsx檔案相鄰。
src/components/Hello.test.tsx
import * as React from 'react'; import * as enzyme from 'enzyme'; import Hello from './Hello'; it('renders the correct text when no enthusiasm level is given', () => { const hello = enzyme.shallow(<Hello name='Durban' />); expect(hello.find('.greeting').text()).toEqual('Hello Durban!'); }); it('renders the correct text with an explicit enthusiasm of 1', () => { const hello = enzyme.shallow(<Hello name='Durban' enthusiasmLevel={1} />); expect(hello.find('.greeting').text()).toEqual('Hello Durban!'); }); it('renders the correct text with an explicit enthusiasm of 5', () => { const hello = enzyme.shallow(<Hello name='Durban' enthusiasmLevel={5} />); expect(hello.find('.greeting').text()).toEqual('Hello Durban!!!!!'); }); it('throws when the enthusiasm level is 0', () => { expect(() => { enzyme.shallow(<Hello name="Durban" enthusiasmLevel={0} />); }).toThrow(); }); it('throws when the enthusiasm level is negative', () => { expect(() => { enzyme.shallow(<Hello name='Durban' enthusiasmLevel={-1} />); }).toThrow(); });
這些測試非常基礎,但你應該能夠掌握一切。
執行程式碼
npm run test
即可看到執行通過測試的結果
小提示
如果你在國內的話,建議將test的命令
"test": "react-scripts-ts test --env=jsdom",
改為
"test": "react-scripts-ts test --env=jsdom --watchman=false",
這個原因是因為。預設啟動了watchman,watchman是需要連線國外的,如果在國內的話,會因為連線不上導致,看不到測試結果
執行後的結果類似如下
PASSsrc/App.test.tsx PASSsrc/components/Hello.test.tsx Test Suites: 2 passed, 2 total Tests:6 passed, 6 total Snapshots:0 total Time:3.68s Ran all test suites related to changed files. Watch Usage › Press p to filter by a filename regex pattern. › Press t to filter by a test name regex pattern. › Press q to quit watch mode. › Press Enter to trigger a test run.
未完待續...