前端自動化測試實踐02—jest基本語法

前端自動化測試實踐02—jest基本語法

Write By CS逍遙劍仙
我的主頁: www.csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: [email protected]

本節代碼地址 https://github.com/csxiaoyaojianxian/JavaScriptStudy 下的自動化測試目錄

1. matchers 匹配器

測試工具中最基本的就是斷言匹配器,下面是 jest 中常用的匹配器。

【 toBe 】【 toEqual 】

test('jest匹配器', () => {
	const a = 1;
    const b = { one: 1 };
    expect(a).toBe(1);
    // expect(b).toBe({ one: 1 }); // false 地址不同
    expect(b).toEqual({ one: 1 });
})

【 toBeNull 】【 toBeUndefined 】【 toBeDefined 】【 toBeTruthy 】【 toBeFalsy 】

test('jest匹配器', () => {
	expect(null).toBeNull();
})

【 not 】

test('jest匹配器', () => {
	expect(1).not.toBeFalsy();
})

Number

【 toBeCloseTo 】【 toBeGreaterThan 】【 toBeLessThan 】【 toBeGreaterThanOrEqual 】【 toBeLessThanOrEqual 】

test('jest匹配器', () => {
    expect(10).toBeGreaterThanOrEqual(10);
    expect(0.1 + 0.2).toBeCloseTo(0.3);
})

String

【 toMatch 】

test('jest匹配器', () => {
	expect('www.csxiaoyao.com').toMatch('csxiaoyao');
})

Array/Set

【 toContain 】

test('jest匹配器', () => {
    const a = ['www', 'csxiaoyao', 'com'];
    expect(a).toContain('csxiaoyao');
    expect(new Set(a)).toContain('csxiaoyao');
})

Object

【 toMatchObject 】

test('jest匹配器', () => {
    expect({ data: { success: true } }).toMatchObject({ data: { success: true } });
})

異常

【 toThrow 】

test('jest匹配器', () => {
    const a = () => { throw new Error('this is a new error') };
    expect(a).toThrow();
    expect(a).toThrow('this is a new error');
    expect(a).toThrow(/this is a new error/);
    // expect(a).not.toThrow(); // 沒有拋出異常
})

其他

【 any 】…

2. hook 鉤子函數

beforeAll / afterAll / beforeEach / afterEach

beforeAll(() => {
	console.log('beforeAll')
})
afterAll(() => {
	console.log('afterAll')
})
// 每個用例執行前執行,一般用於針對不同用例初始化不同的實例對象
beforeEach(() => {
	console.log('beforeEach')
    // 實例化
    counter = new Counter()
})
afterEach(() => {
	console.log('afterEach')
})

3. describe 分組

可以用於限定作用域,可以與鉤子函數配合使用,寫在不同層級的鉤子函數,作用域不同

describe('測試分組和鉤子函數', () => {
    let counter = null
    // 外層 beforeEach
    beforeEach(() => { counter = new Counter() })
    // 分組1
    describe('測試分組1代碼', () => {
        // 【 使用 describe 限定作用域 】
        // 內層 beforeEach 不會對後面的同級 describe 產生影響
        beforeEach(() => { console.log('beforeEach test group1') })
        test('xxx', () => { /* ... */ })
        // ...
    })
    // 分組2
    describe('測試分組2代碼', () => {
        test('xxx', { /* ... */ })
        // ...
    })
})

4. only 跳過 case

test('該 case 被跳過', () => { /* ... */ })
test.only('只測試這個用例,跳過其他 case', () =>{ /* ... */ })
test('該 case 被跳過', () => { /* ... */ })

5. snapshot 快照測試

快照測試適用於配置文件、UI等內容的測試,快照保存上次運行的結果存儲在 __snapshots__ 下,如果兩次執行結果不一致則不通過,需要檢查後更新快照,按 u 更新全部快照,按 i 進入交互式單獨更新。例如測試下面的配置文件 snapshot.js

// 固定值
export const generateConfig1 = () => {
    return {
        server: 'http://localhost',
        port: 8080
    }
}
// 存在變化的時間值
export const generateConfig2 = () => {
    return {
        server: 'http://localhost',
        port: 8080,
        time: new Date()
    }
}

編寫測試用例,注意匹配時間類變化值

import { generateConfig1, generateConfig2 } from "./11-snapshot";
test("測試 generateConfig1 函數", () => {
	expect(generateConfig1()).toMatchSnapshot();
});
test("測試 generateConfig2 函數", () => {
	expect(generateConfig2()).toMatchSnapshot({
		// 用於匹配時間類變化的值
        time: expect.any(Date)
	});
});

inline snapshot,可以將快照保存在用例中,需要安裝 prettier 模塊

$ npm install prettier --save

編寫測試用例

test("測試 generateConfig2 函數 inline", () => {
	expect(generateConfig2()).toMatchInlineSnapshot({
		time: expect.any(Date)
	});
});

執行後快照保存在用例文件中

test("測試 generateConfig2 函數 inline", () => {
	expect(generateConfig2()).toMatchInlineSnapshot({
			time: expect.any(Date)
    	},
        `
        Object {
            "port": 8080,
            "server": "http://localhost",
            "time": Any<Date>,
        }
  		`
	);
});

6. DOM 測試

dom 測試一般用於測試 UI,例如需要測試下面 jquery 操作 dom 的代碼 dom.js

import { jsdom } from 'jsdom'
import $ from 'jquery'
const addDivToBody = () => {
	$('body').append('<div/>')
};
export default addDivToBody

編寫測試用例,node 不具備 dom,因此 jest 在 node 環境下模擬了 dom api — jsDom

import addDivToBody from './dom'
import $ from 'jquery'
test('測試 addDivToBody', () => {
    addDivToBody()
    addDivToBody()
    expect($('body').find('div').length).toBe(2)
})

發佈了133 篇原創文章 · 獲贊 13 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章