Jest 新手入門筆記

1. 匹配器 Matchers

test('two plus two is four', () => {
    expect(2 + 2).toBe(4);
});
複製代碼

test() 別名 it()javascript

expect(...).not.toBe(...) 測試相反的匹配java

普通匹配器

  • toBe 使用的是Object.is()判斷兩個值是否相等, 若是判斷object的話要使用toEqual代替。android

  • toEqual 遞歸檢查對象或數組的每一個字段。ios

  • toBeNull 只匹配 null正則表達式

  • toBeUndefined 只匹配 undefinedjson

  • toBeDefinedtoBeUndefined 相反axios

  • toBeTruthy 匹配任何 if 語句爲真數組

  • toBeFalsy 匹配任何 if 語句爲假promise

數字:

  • toBeGreaterThan 大於
  • toBeGreaterThanOrEqual 大於等於
  • toBeLessThan 小於
  • toBeLessThanOrEqual 小於等於
  • toBeCloseTo 比較浮點數相等,忽略舍入偏差

字符串:

  • toMatch 使用正則表達式匹配字符串
  • toContain 檢查數組或可迭代對象是否包含某個特定選項
test('there is no I in team', () => {
    expect('team').not.toMatch(/I/)
})
複製代碼

測試異常toThrow

function compileAndroidCode(){
    throw new Error('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
    expect(compileAndroidCode).toThrow();
    expect(compileAndroidCode).toThrow(Error);
    // You can also use the exact error message or a regexp
    expect(compileAndroidCode).toThrow('you are using the wrong JDK');
    expect(compileAndroidCode).toThrow(/JDK/);
})
複製代碼

完整的匹配器列表, 請查閱 參考文檔bash

2. 測試異步代碼

1. done參數 回調

使用單個參數 done 函數,Jest會等 done() 回調函數執行結束後結束測試。若是done永遠不會調用,這個測試將失敗。

test('the data is peanut butter', done => {
    function callback (data) {
        expect(data).toBe('peanut butter');
        done();
    }
    // fetchData 是待測試的異步函數
    fetchData(callback);
})
複製代碼

2. Promise

test 返回一個Promise, Jest 會等到Promise完成調用resolve方法後結束,若是rejected, 測試自動失敗。

test('the data is peanut butter', () => {
    return fetchData().then(data => {
        expect(data).toBe('peanut butter');
    })
})
複製代碼

必定不要忘記把 promise 做爲返回值。若是你忘了 return語句的話,在 fetchData 返回的這個 promiseresolvethen() 有機會執行以前,測試就已經被視爲已經完成了。

3. Async/Await

test('the data is peanut butter', async () => {
    const data = await fetchData();
    expect(data).toBe('peanut butter');
})
複製代碼
test('the fetch fails with an error', async () => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch('error');
  }
});
複製代碼

3. setup and teardown

Jest提供輔助函數beforeEach, beforeAfter, beforeAll, beforeAfter處理運行測試前、後的一些工做。
默認狀況下,beforeafter中的塊能夠應用到文件中的每個測試。此外,能夠使用describe塊將測試分組。describe塊內的beforeafter只適用於該describe塊內部。文件頂部的before after先執行,describe塊內的before after後執行。

// 一次性設置,只須要在文件的開頭作一次設置。
beforeAll(() => {
    initDatabase();
})

afterAll(() => {
    clearDatabase();
})

beforeEach(() => {
    initData(); // 每一個測試以前調用
})

afterEach(() => {
    clearData(); // 每一個測試後調用
})

test('do test1', () => {
    expect(...).toBe(...)
})

test('do test2', () => {
    expect(...).toBe(...)
})

describe('some tests', () => {
    beforeEach(() => {
        initSomeData();
    })
    
    test('test in describe', () => {
        ...
    })
})

複製代碼

4. test.only

但測試失敗時,第一件要檢查的事就是,當僅運行這一條測試時,是否仍然失敗。方法就是把test改爲test.only

test.only('this will be the only test that runs', () => {
  expect(true).toBe(false);
});

test('this test will not run', () => {
  expect('A').toBe('A');
});
複製代碼

5. mock函數

jest.fn

.mock 屬性

全部的mock函數都有一個特殊的 .mock 屬性,它保存了關於此函數如何被調用、調用時的返回值信息。 .mock屬性還追蹤每次調用時this的值.mock.instances

const mockFn = jest.fn()

mockFn.mock.calls.length mock方法調用的次數

mockFn.mock.calls[i][j] 第i次調用時的第j個參數

mockFn.mock.results[i] 第i次調用時的返回值

mockFn.mock.instances[i] 第i次調用時的this

mock 返回值

mock方法也能夠用來在測試代碼中注入測試值。

  • mockFn.mockReturnValueOnce()
  • mockFn.mockReturnVaule()
const filterTestFn = jest.fn();

// Make the mock return `true` for the first call,
// and `false` for the second call
filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false);

const result = [11, 12].filter(filterTestFn);

console.log(result);
// > [11]
console.log(filterTestFn.mock.calls);
複製代碼

mock Promise返回值

jest.mock(...) mockResolveValue

import axios from 'axios';

class Users {
    static all(){
        return axios.get('/user.json').then(resp => resp.data)
    }
}

export default Users;
複製代碼

測試代碼以下:

import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
    const users = [{name: 'Blob'}]
    const resp = {data: users};
    axios.get.mockResolvedValue(resp);
    return Users.all().then(data => expect(data).toEqual(users));
})
複製代碼

mock 方法的實現

  • mockImplementation
  • mockImplementationOnce
  • mockReturnThis 鏈式方法
const myObj = {
  myMethod: jest.fn().mockReturnThis(),
};

// is the same as
const otherObj = {
  myMethod: jest.fn(function() {
    return this;
  }),
};
複製代碼

6. Snapshot Testing 快照測試

快照測試是測試你的渲染組件的圖片,並將其與組件的之前的圖片進行比較。

相關文章
相關標籤/搜索