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
只匹配 undefined
json
toBeDefined
與 toBeUndefined
相反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
done
參數 回調使用單個參數 done
函數,Jest會等 done()
回調函數執行結束後結束測試。若是done
永遠不會調用,這個測試將失敗。
test('the data is peanut butter', done => {
function callback (data) {
expect(data).toBe('peanut butter');
done();
}
// fetchData 是待測試的異步函數
fetchData(callback);
})
複製代碼
test 返回一個Promise
, Jest 會等到Promise
完成調用resolve
方法後結束,若是rejected
, 測試自動失敗。
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
})
})
複製代碼
必定不要忘記把 promise
做爲返回值。若是你忘了 return
語句的話,在 fetchData
返回的這個 promise
被 resolve
、then()
有機會執行以前,測試就已經被視爲已經完成了。
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');
}
});
複製代碼
Jest提供輔助函數beforeEach
, beforeAfter
, beforeAll
, beforeAfter
處理運行測試前、後的一些工做。
默認狀況下,before
和after
中的塊能夠應用到文件中的每個測試。此外,能夠使用describe
塊將測試分組。describe
塊內的before
和after
只適用於該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', () => {
...
})
})
複製代碼
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');
});
複製代碼
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方法也能夠用來在測試代碼中注入測試值。
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);
複製代碼
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));
})
複製代碼
mockImplementation
mockImplementationOnce
mockReturnThis
鏈式方法const myObj = {
myMethod: jest.fn().mockReturnThis(),
};
// is the same as
const otherObj = {
myMethod: jest.fn(function() {
return this;
}),
};
複製代碼
快照測試是測試你的渲染組件的圖片,並將其與組件的之前的圖片進行比較。