入門
安裝
npm init -y
npm i @babel/core @babel/preset-env [email protected] -D
配置
//添加.babelrc
{
"presets":[
["@babel/preset-env",{
"targets":{
"node":"current"
}
}]
]
}
//package.json添加
"scripts":{
"test":"jest --watchAll"
}
編碼
// 根目錄添加 index.js
export const add = (a, b) => {
return a + b;
};
export const reduce = (a, b) => {
return a - b;
};
// 根目錄添加 index.test.js
import { add, reduce } from "./index";
test("測試add函數", () => {
expect(add(1, 2)).toBe(3);
});
test("測試reduce函數", () => {
expect(reduce(3, 1)).toBe(2);
});
運行
jest
的時候jest
會自動檢測到你後綴名爲.test.js
的文件
運行
npm run test
結果
Jest
裏面常用的匹配器
test(描述 ,執行測試片段)
import { add, reduce } from "./index";
// toBe 數字
test("測試add函數", () => {
expect(add(1, 2)).toBe(3);
});
test("測試reduce函數", () => {
expect(reduce(3, 2)).toBe(1);
});
// toEqual:測試對象中的值是否與測試結果一致
test("測試對象中的值是否與測試結果一致", () => {
expect({ a: 1 }).toEqual({ a: 1 });
});
// toHaveLength:判斷字符串或者數組的長度
test("判斷字符串或者數組的長度", () => {
expect([1, 2, 3, 4, 5, 6, 7]).toHaveLength(7);
});
// toMatch:值是一個正則表達式 匹配字符串中是否存在某個字符
test("匹配字符串中是否存在某個字符", () => {
expect("qwertyui").toMatch("qwe");
});
//測試值是否爲null
test("測試toBeNull", () => {
var n = null;
expect(n).toBeNull();
});
//測試值是否爲undefined
test("測試toBeUndefined", () => {
var a = undefined;
expect(a).toBeUndefined();
});
// only 跳過其他測試用例 只測試當前這個用例
test.only("測試toBeDefined",()=>{
var a = "";
expect(a).toBeDefined();
})
//測試值是否爲true
test("測試toBeTruthy", () => {
var flag = true;
expect(flag).toBeTruthy();
});
//測試值是否爲false
test("測試toBeFalsy", () => {
expect(false).toBeFalsy();
});
//測試數組中是否存在某個值
test("toContain", () => {
var arr = [10, 20, 30, 40];
expect(arr).toContain(10);
});
//測試浮點數
test("toBeCloseTo", () => {
var n = 0.1;
var m = 0.2;
// toBe(0.3)將報錯因爲,二進制計算的原因
expect(n + m).toBeCloseTo(0.3);
});
//測試值要大於等於預期值
test("toBeGreaterThanOrEqual", () => {
expect(10).toBeGreaterThanOrEqual(10);
});
//測試值要小於等於預期值
test("toBeLessThanOrEqual", () => {
expect(9).toBeLessThanOrEqual(9);
});
//測試值要大於預期值
test("toBeGreaterThan", () => {
expect(10).toBeGreaterThan(9);
});
//測試值要小於預期值
test("toBeLessThan", () => {
expect(8).toBeLessThan(9);
});
//檢測當前方法中是否拋出異常
test("toThrow", () => {
expect(fn).toThrow();
});
/*********測試異步代碼*********** */
// axios請求
import { fetchData } from "./index.js";
//基於promise
test("測試異步代碼", () => {
return fetchData().then(data => {
expect(data.data).toEqual({ success: true });
});
});
// async await
test("測試異步代碼", async () => {
var data = await fetchData();
expect(data.data).toEqual({ success: true });
});
// 測試對的
test("異步測試", () => {
return expect(fetchData()).resolves.toMatchObject({
data: {
success: true
}
});
});
// 測試錯的
test("異步測試失敗", () => {
return expect(fetchData()).rejects.toThrow();
});
// 推薦
test("測試異步代碼", async () => {
var data = await fetchData();
expect(data.data).toMatchObject({ success: true });
});