1. 程式人生 > >Jest-Javascript單元測試工具

Jest-Javascript單元測試工具


 
  
   
    

    
     

Jest是一個JavaScript測試框架,由Facebook用來測試所有JavaScript程式碼,包括React應用程式。

不同級別的自動化測試:單元、整合、元件和功能. 單元測試可以看作是和在元件級別測試JavaScript物件和方法一樣的最基本的。預設情況下,React Native提供在Android和iOS都可以使用的Jest來進行單元測試。現在,測試的覆蓋率並不完美,但是根據Facebook的說法,未來將會有更強大測試能力的工具被引入到React Native,同時使用者也可以構建他們自己的測試工具。

Jest的測試特性

適應性:Jest是模組化、可擴充套件和可配置的。

快速和沙盒:Jest虛擬化JavaScript環境,能模擬瀏覽器,並在工作程序之間並行執行測試。

快照測試:Jest能夠對React 樹進行快照或別的序列化數值快速編寫測試,提供快速更新的使用者體驗。

快速互動模式: 錯誤資訊會有幫助的顏色編碼標記,堆疊跟蹤快速指向問題的根源。

使用

配置Jest

可以使用npm執行 **npm install --save-dev jest**  也可以與使用所有的Js包一樣:先配置package.json,再執行npm install。

編寫測試指令碼

1.讓我們寫一個假設的測試是sum.js檔案,函式為:

module.exports = (a, b) => a + b;

2.建立一個目錄____tests____/和檔案xxx-test.js,或直接建立名稱xxx.test.js或xxx.spec.js並把它放在你的專案的任何地方(**其實在jest中我們對腳步的定義是有約束的,採用這幾鍾建立方式,使jest在原始碼檔案中可以找到測試腳步並執行**)

test('adds 1 + 2 to equal 3', () => {

const sum = require('../sum');

expect(sum(1, 2)).toBe(3);

});

3.執行指令碼  (執行指令碼有兩種方式)

1)可以新增到package.json

"scripts": {

"test": "jest"

}

2)直接執行命令

需要安裝全域性jest命令: npm install -g jest,進入專案,執行命令:jest

4.執行

執行**npm test**會列印此訊息:**PASS ____tests____/sum-test.js** 到此你就成功使用Jest寫了你的第一個測試!


所有的斷言

.expect(value)

.lastCalledWith(arg1, arg2, ...) is an alias for .toHaveBeenLastCalledWith(arg1, arg2, ...)

.not

.toBe(value)

.toBeCalled() is an alias for .toHaveBeenCalled()

.toBeCalledWith(arg1, arg2, ...) is an alias for .toHaveBeenCalledWith(arg1, arg2, ...)

.toHaveBeenCalled()

.toHaveBeenCalledTimes(number)

.toHaveBeenCalledWith(arg1, arg2, ...)

.toHaveBeenLastCalledWith(arg1, arg2, ...)

.toBeCloseTo(number, numDigits)

.toBeDefined()

.toBeFalsy()

.toBeGreaterThan(number)

.toBeGreaterThanOrEqual(number)

.toBeLessThan(number)

.toBeLessThanOrEqual(number)

.toBeInstanceOf(Class)

.toBeNull()

.toBeTruthy()

.toBeUndefined()

.toContain(item)

.toContainEqual(item)

.toEqual(value)

.toHaveLength(number)

.toMatch(regexp)

.toMatchObject(object)

.toMatchSnapshot()

.toThrow()

.toThrowError(error)

.toThrowErrorMatchingSnapshot()

作者:小濤先生呢 連結:https://www.jianshu.com/p/a656a5459e73 來源:簡書 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。