前端單元測試入門2-jest

1.經常使用測試框架

  • qunit jQuery
  • mocha 支持Node&Browser express.js
  • jasmine支持Node&Browser Vue.js
  • karma A Test-Runner 在不一樣的瀏覽器中跑測試用例 Angular
  • jest Reactcss

    • 零配置
    • 內置代碼覆蓋率
    • 內置Mocks

2 jest

2.1 安裝

npm i jest --save-dev 
npm i jest -g

2.2 編寫

**/test.jshtml

2.3 運行

npx run jest
npm run test(配置scripts)

2.4 編寫測試用例

  • Test Suits 測試套件,每一個文件就是一個套件
  • Test Group 分組 describe
  • Test Case 測試用途 test()
  • Assert 斷言 expect()
//qs.test.js
let { parse, stringify } = require('./qs');
describe('parse', () => {//分組
    test('one', () => {//測試用例
        expect(parse("name=zfpx").name).toBe('zfpx');
    });
    test('two', () => {
        expect(parse("name=zfpx&age=9").age).toBe('9');
    });
});


describe('stringify', () => {
    test('one', () => {
        expect(stringify({ name: 'zfpx' })).toBe('name=zfpx');
    });
    test('two', () => {
        expect(stringify({ name: 'zfpx', age: 9 })).toBe('name=zfpx&age=9');
    });
});

2.5 配置

2.5.1 配置位置

  • package.json
  • jest.config.js(推薦)
  • 命令行

2.5.2 配置項

  • testMatch glob規則,識別哪些文件中測試文件
  • testRegex 文件正則
  • testEnvironment 測試環境
  • rootDir 根目錄
  • moduleFileExtensions 模塊文件擴展名

具體的配置項可參數後續的2.10附錄node

module.exports = {
    //設置識別哪些文件是測試文件(glob形式),與testRegex互斥,不能同時寫
    testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)'],
    //設置識別哪些文件是測試文件(正則形式),與testMatch互斥,不能同時寫
    testRegex: '(/__tests__).*|(\\.|/)(test|spec))\\.jsx?$',
    //測試環境,默認值是:jsdom,可修改成node
    testEnvironment: 'jsdom',
    //默認值:當前目錄,通常是package.json所在的目錄。
    rootDir: '',
    //測試文件的類型
    moduleFileExtensions: ['js', 'json', 'jsx', 'node']
}

2.5.3 Matchers

  • 相等斷言git

    • toBe(value): 比較數字、字符串
    • toEqual(value): 比較對象、數組
    • toBeNull()
    • toBeUndefined()
  • 包含斷言github

    • toHaveProperty(keyPath, value): 是否有對應的屬性
    • toContain(item): 是否包含對應的值,括號裏寫上數組、字符串
    • toMatch(regexpOrString): 括號裏寫上正則
  • 邏輯斷言,在JavaScript中,有六個falsy值:false,0,'',null, undefined,和NaN。其餘一切都是Truthy。express

    • toBeTruthy()
    • toBeFalsy()
    • toBeGreaterThan(number): 大於
    • toBeLessThan(number): 小於
  • not 取反
test('matchers', () => {
    const a = {
        name: 'a',
        home: {
            name: 'beijing'
        }
    }
    const b = {
        name: 'a',
        home: {
            name: 'beijing'
        }
    }
    expect(a).toEqual(b)
    expect([1, 2, 3]).toEqual([1, 2, 3])
    expect(null).toBeNull()

    expect([1, 2, 3]).toContain(1)
    expect(b).toHaveProperty('home')
    expect('abc').toContain('b')
    expect('abc').toMatch(/^\w+$/)
    expect('123').not.toContain('4')
})

2.6 DOM測試

  • jsdom
  • Jest能操做DOM是由於內置了JSDOM
  • JSDOM是在node中模擬了DOM環境
//dom.js
function remove(node) {
    node.parentNode.removeChild(node);
}
function on(node, type, handler) {
    node.addEventListener(type, handler);
}
exports.remove = remove;
exports.on = on;
//dom.test.js
let { remove, on } = require('./dom');
describe('dom', () => {
    test('remove', () => {
        document.body.innerHTML = '<div id="container"><span id="hello">hello</span></div>';
        let container = document.getElementById('container');
        expect(container.nodeName.toLocaleLowerCase()).toBe('div');
        let hello = document.getElementById('hello');
        expect(hello.nodeName.toLocaleLowerCase()).toBe('span');
        remove(hello);
        let hello2 = document.getElementById('hello');
        expect(hello2).toBeNull();
    })

    test('on', () => {
        document.body.innerHTML = '<div id="container"><button id="clickMe">click</button></div>';
        let clickMe = document.getElementById('clickMe');
        on(clickMe, 'click', () => {
            clickMe.innerHTML = 'clicked';
        });
        clickMe.click();
        expect(clickMe.innerHTML).toBe('clicked');

    })
});

2.7 測試選項卡

tab.htmlnpm

<div id="tab">
    <div>
        <a href="#" class="tab-button">選項1</a>
        <a href="#" class="tab-button">選項2</a>
    </div>
    <div>
        <div class="tab-panel">面板1</div>
        <div class="tab-panel">面板2</div>
    </div>
</div>

Tab.jsjson

class Tab{
    constructor(id,buttonClass,panelClass){
        this.tab = tab = document.querySelector('#'+id);
        this.buttons = Array.from(tab.querySelectorAll('.'+buttonClass));
        this.panels = Array.from(tab.querySelectorAll('.'+panelClass));
        this.select(0);
        this.bindEvent();
    }
    select(index){
        this.buttons.forEach(button=>button.style.backgroundColor= 'white');
        this.buttons[index].style.backgroundColor= 'red';
        this.panels.forEach(panel=>panel.style.display= 'none');
        this.panels[index].style.display= 'block';
    }
    bindEvent(){
        for(let i=0;i<this.buttons.length;i++){
            this.buttons[i].addEventListener('click',()=>{
                this.select(i);
            });
        }
    }
}
module.exports = Tab;

Tab.test.jsgulp

const Tab = require('../src/tab');
const fs = require('fs');
const path = require('path');

test('tab',function(){
    document.body.innerHTML = fs.readFileSync(path.resolve(__dirname,'tab.html'),'utf8');
    const tab = new Tab('tab','tab-button','tab-panel');
    expect(tab.buttons[0].style.backgroundColor).toBe('red');
    expect(tab.buttons[1].style.backgroundColor).toBe('white');
    expect(tab.panels[0].style.display).toBe('block');
    expect(tab.panels[1].style.display).toBe('none');
    tab.buttons[1].click();
    expect(tab.buttons[0].style.backgroundColor).toBe('white');
    expect(tab.buttons[1].style.backgroundColor).toBe('red');
    expect(tab.panels[0].style.display).toBe('none');
    expect(tab.panels[1].style.display).toBe('block');
});

2.8 異步測試

  • jest默認不會處理異常任務
  • 2.若是函數裏的形參使用了done的話, jest會阻塞在此不往下執行,
  • 3.jest會等待done被調用纔會繼續向下執行
  • 4.超過5000不會執行,會提示 Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
test('async',(done)=>{
    setTimeout(()=>{
        expect(2).toBe(2);
        done();
    },1000);
});

2.9 代碼覆蓋率

  • line coverage 行覆蓋率
  • function coverage 函數覆蓋率
  • branch coverage 分支覆蓋率
  • statement coverage 語句覆蓋率
npm run jest --coverage
npx jest --coverage

2.10附錄

2.10.1 glob

gulp內部使用了node-glob模塊來實現其文件匹配功能。咱們能夠使用下面這些特殊的字符來匹配咱們想要的文件:數組

2.10.2 glob規則

匹配符 說明
匹配文件路徑中的0個或多個字符,但不會匹配路徑分隔符
** 匹配路徑中的0個或多個目錄及其子目錄
[...] 匹配方括號中出現的字符中的任意一個,當方括號中第一個字符爲^或!時,則表示不匹配方括號中出現的其餘字符中的任意一個
!(pattern pattern pattern) 匹配任何與括號中給定的任一模式都不匹配的
?(pattern pattern pattern) 匹配括號中給定的任一模式0次或1次,相似於js正則中的?
+(pattern pattern pattern) 匹配括號中給定的任一模式至少1次,相似於js正則中的+
(pattern pattern pattern) 匹配括號中給定的任一模式0次或屢次,相似於js正則中的 *
@(pattern pattern pattern) 匹配括號中給定的任一模式1次,相似於js正則中的

2.10.3 glob示例

glob 匹配
* 能匹配 a.js,x.y,abc,abc/,但不能匹配a/b.js
. a.js,style.css,a.b,x.y
//*.js 能匹配 a/b/c.js,x/y/z.js,不能匹配a/b.js,a/b/c/d.js
** 能匹配 abc,a/b.js,a/b/c.js,x/y/z,x/y/z/a.b,能用來匹配全部的目錄和文件
a/**/z 能匹配 a/z,a/b/z,a/b/c/z,a/d/g/h/j/k/z
a/**b/z 能匹配 a/b/z,a/sb/z,但不能匹配a/x/sb/z,由於只有單**單獨出現才能匹配多級目錄
?.js 能匹配 a.js,b.js,c.js
a?? 能匹配 a.b,abc,但不能匹配ab/,由於它不會匹配路徑分隔符
[xyz].js 只能匹配 x.js,y.js,z.js,不會匹配xy.js,xyz.js等,整個中括號只表明一個字符
[^xyz].js 能匹配 a.js,b.js,c.js等,不能匹配x.js,y.js,z.js
相關文章
相關標籤/搜索