使用Jest測試Typescript

這個博客的粉絲不須要深信良好維護的測試套件(針對karma+jasmine?)的價值。幸運的是Jest使得測試React應用變得很是輕鬆,即便使用了Typescript,也是如此。讓咱們深刻研究開發純淨的、測試安全的代碼所涉及的各個層面。html

Linting

在vanilla Javascript中,linters是按一種風格來驗證語法,這也是防止運行時錯誤的第一道防線。在Typescript中,靜態類型檢查具備相似的用途,但對原始語法的上下文有更復雜的理解。可是,linters仍然爲維護者增長了價值:即便使用類型系統處理繁重的靜態分析,咱們仍然能夠從清晰,一致的風格中受益。
tslint是很是好的 Typescript linter,與Javascript工具jshint/eslint提供相同的功能。node

npm i -g tslint
tslint --init

安裝tslint並初始化默認配置,咱們就能夠對新項目或現有項目進行lint:react

rslint -c tslint.json '/src/**/*.{ts,tsx}'
// tslint.json 我進行了擴展
{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {
        "max-line-length": {
            "options": [120]
        }
    },
    "rules": {
        "max-line-length": {
            "options": [120]
        },
        "new-parens": true,
        "no-arg": true,
        "no-bitwise": true,
        "no-conditional-assignment": true,
        "no-consecutive-blank-lines": false,
        "no-console": {
            "severity": "warning",
            "options": ["debug", "info", "log", "time", "timeEnd", "trace"]
        },
        "quotemark": [true, "single", "avoid-escape", "avoid-template"],
        "member-access": false,
        "interface-name": false
    },
    "rulesDirectory": []
}

使用Jest進行單元測試

Jest是一種在React應用程序中很流程的測試工具,能夠進行簡單的配置,就能夠工做--低配置化工具。 【and for good reason: in vanilla JavaScript, it mostly Just Works™.】
將Jest與Typescript一塊兒使用須要更多的工做。Facebook的Jest/TypeScript示例概述了該策略:設置一個預處理器,如ts-jest處理編譯和源映射,而後將處理過的文件提供給Jest。webpack

npm i --save-dev ts-jest

要配置Jest,讓咱們"jest"在項目中添加一個新配置,package.json並使用它來預處理源文件。git

{
  "...": "...",
  "jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
  }
}

package.json是開放的,咱們能夠添加lint和test腳本.github

{
  "...": "...",

  "scripts": {
    "lint": "tslint -c tslint.json 'src/**/*.{ts,tsx}'",
    "pretest": "npm run lint",
    "test": "jest"
  }
}

添加一些測試

此時,咱們能夠編寫一個簡短的示範來獲取<Counter />組件的顯示結果,和Jest快照web

// src/components/__tests__/counter_spec.tsx
import * as React from 'react'
import * as TestUtils from 'react-dom/test-utils'
import * as ReactShallowRenderer from 'react-test-renderer/shallow'

import { createStore } from 'redux'

import { Counter } from '../counter'
import { reducers } from '../../reducers'

describe('<Counter />', () => {
  it('renders', () => {
    const store = createStore(reducers)
    const renderer = new ReactShallowRenderer()

    expect(renderer.render(
      <Counter label='a counter!' store={store} />
    )).toMatchSnapshot()
  })
});

雖然咱們將ReactShallowRenderer開始使用,但可使用相同的設置來使用Enzyme測試組件。不管咱們使用哪一種渲染器,咱們均可以像在Javascript中同樣比較快照。
剩下就是看測試變成綠色。typescript

npm test

測試 reducers

Redux reducers 應該易於測試。使用與組件相同的工具,咱們能夠經過重放一系列操做並比較結果狀態來驗證reducer行爲:npm

// src/reducers/__tests__/index_spec.tsx
import reducers, {
  initialState,
} from '../index'

import {
  incrementCounter
} from '../../actions'

const resultOf = actions =>
  actions.reduce(reducers, initialState)

describe('reducers/counter', () => {
  it('starts at 0', () =>
    expect(resultOf([])).toMatchSnapshot())

  it('increments to 6', () =>
    expect(resultOf([
      incrementCounter(1),
      incrementCounter(2),
      incrementCounter(3),
    ])).toMatchSnapshot())
})

結論

你有它:基本的工具,配置和腳本,使測試成爲TypeScript應用程序的核心部分。咱們沒必要在這裏停下來!雖然這是另外一天的練習,但咱們用於驗證代碼和編寫單元測試的相同技術也能夠輕鬆應用於端到端測試。json

完成的計數器項目可供github,測試和全部參考。有評論,建議或改進嗎?問題隊列是開放的業務。我期待着您在twitter上的建議,經驗和反饋。

和以往同樣,快樂的測試!

我的的github項目地址

相關文章
相關標籤/搜索