Jest 是 Facebook 的一套開源的 JavaScript 測試框架,它自動集成了斷言、JSDom、覆蓋率報告等開發者所須要的全部測試工具,是一款幾乎零配置的測試框架。react
使用 yarn 安裝 Jestandroid
yarn add --dev jest
複製代碼
或 npm:正則表達式
npm install --save-dev jest
複製代碼
首先來編寫第一個求和函數 sum.jsnpm
function sum(a, b){
return a + b;
}
module.exports = sum;
複製代碼
接下來建立測試用例:json
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
})
複製代碼
在 package.json 中配置測試啓動腳本:數組
{
"scripts": {
"test": "jest"
}
}
複製代碼
最後,運行 yarn test 或 npm run test ,Jest 將打印下面這個消息:bash
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
複製代碼
最簡單的測試方法是比較是否精確匹配框架
test(`two plus tow is four`, () => {
expect(2 + 2).toBe(4);
})
複製代碼
在測試中,有時須要精準區分 undefined 、null 和 false,有時 又不須要區分,jest 都知足。異步
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
複製代碼
大多數的比較數字有等價的匹配器。async
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
複製代碼
對於比較浮點數相等,使用 toBeCloseTo 而不是 toEqual,由於你不但願測試取決於一個小小的舍入偏差。
test('兩個浮點數字相加', () => {
const value = 0.1 + 0.2;
//expect(value).toBe(0.3); 這句會報錯,由於浮點數有舍入偏差
expect(value).toBeCloseTo(0.3); // 這句能夠運行
});
複製代碼
toMatch 正則表達式的字符串︰
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
複製代碼
你能夠經過 toContain 來檢查一個數組或可迭代對象是否包含某個特定項:
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('the shopping list has beer on it', () => {
expect(shoppingList).toContain('beer');
expect(new Set(shoppingList)).toContain('beer');
});
複製代碼
測試的特定函數拋出一個錯誤,在它調用時,使用 toThrow。
function compileAndroidCode() {
throw new ConfigError('you are using the wrong JDK');
}
test('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(ConfigError);
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK');
expect(compileAndroidCode).toThrow(/JDK/);
});
複製代碼
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
複製代碼
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
複製代碼
.resloves/.rejects
test('the data is peanut butter', () => {
return expect(fetchData()).resolves.toBe('peanut butter');
});
複製代碼
test('the fetch fails with an error', () => {
return expect(fetchData()).rejects.toMatch('error');
});
複製代碼
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');
}
});
複製代碼
用於在寫測試的時候 須要運行測試前作的一些 準備工做,和在運行測試後進行的一些整理工做。
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
複製代碼
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
複製代碼
默認狀況下,before 和 after 的塊能夠應用到文件中的每一個測試。 此外能夠經過 describe 塊來將測試分組。 當 before 和 after 的塊在 describe 塊內部時,則其只適用於該 describe 塊內的測試。
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 sausage', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
複製代碼
function forEach(items, callback) {
for (let index = 0; index < items.length; index++) {
callback(items[index]);
}
}
const mockCallback = jest.fn(x => 42 + x);
forEach([0, 1], mockCallback);
// The mock function is called twice
expect(mockCallback.mock.calls.length).toBe(2);
// The first argument of the first call to the function was 0
expect(mockCallback.mock.calls[0][0]).toBe(0);
// The first argument of the second call to the function was 1
expect(mockCallback.mock.calls[1][0]).toBe(1);
// The return value of the first call to the function was 42
expect(mockCallback.mock.results[0].value).toBe(42);
複製代碼
const myMock = jest.fn();
console.log(myMock());
// > undefined
myMock
.mockReturnValueOnce(10)
.mockReturnValueOnce('x')
.mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
// > 10, 'x', true, true
複製代碼
使用快照功能給組件作快照,方便後面調整後與快照對比
使用 React 的 test renderer 和 Jest 的快照特性來和組件交互,得到渲染結果和生成快照文件:
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';
test('Link changes the class when hovered', () => {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseLeave();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
複製代碼