Jest实战案例

时游大约 2 分钟

Jest 实战案例

案例 1:ToFixed 函数测试

/plugins/index.js 文件

export default {
	/**
	 *	格式化数字、字符串,小数位数默认2位
	 *  例:电压精确小数点3位
	 *      0  -> 0
	 * 	    0.00  -> 0
	 *      12  -> 12
	 *      12.01  -> 12.01
	 *      12.145  ->  12.145
	 *      12.1456  ->  12.146
	 *      12.1451  ->  12.145
	 *      12.1599  ->  12.16
	 *      12.1999  ->  12.2
	 *      12.9999  ->  13
	 *      -0.0012  ->  0
	 *      -0.00000001  ->  0
	 */
	toFixed(val, length = 2) {
		//不是数字,返回-
		if (isNaN(parseFloat(val))) {
			return "-";
		}
		if (["number", "string"].includes(typeof val)) {
			if (val == 0) return 0;
			if (String(val).match(/\./) || String(val).includes("e-")) {
				let newVal = parseFloat(Number(val).toFixed(length));
				if (newVal === 0) return 0; //转换后有可能是 -0
				return newVal;
			} else {
				return val;
			}
		}
		return "-";
	}
};

/tests/toFixed.test.js 文件

/** 针对toFixed函数的单元测试
 */
const { toFixed } = require("@/src/plugins/index.js").default;

describe("测试toFixed方法", () => {
	// 主描述
	it("0测试", () => {
		// 测试用例1
		expect(toFixed(0)).toBe(0);
	});
	it("0.00测试", () => {
		// 测试用例2
		expect(toFixed(0.0)).toBe(0);
	});
	it("12测试", () => {
		expect(toFixed(12)).toBe(12);
	});
	it("12.01测试", () => {
		expect(toFixed(12.01)).toBe(12.01);
	});
	it("12.456测试", () => {
		expect(toFixed(12.456)).toBe(12.46);
	});
});

结果

匹配结果

image-20230901104434099
image-20230901104434099

案例 2:模拟接口测试

Login.vue 文件

<template>
	<div>用户登录</div>
</template>

<script>
	import axios from "axios";
	export default {
		data() {
			return {
				username: "-"
			};
		},
		methods: {
			login({ username, password }) {
				axios
					.post("/login", { username, password })
					.then(res => {
						this.username = res.data.username ?? "-";
					})
					.catch(err => {
						console.log(err);
						throw err;
					});
			}
		}
	};
</script>

login.test.js 文件

/* 用户登录接口测试 */
import { shallowMount } from "@vue/test-utils";
import loginComponent from "@/src/views/Login.vue";

// 模拟axios函数(注意:此方法会临时替换axios模块)
jest.mock("axios", () => ({
	post: jest.fn(() =>
		Promise.resolve({
			data: {
				username: "sunshine",
				password: "a123456"
			}
		})
	)
}));

describe("测试用户登录", () => {
	const loginData = {
		username: "sunshine",
		password: "a123456"
	};
	const wrapper = shallowMount(loginComponent); // 组件挂载
	it("测试登录", async () => {
		await wrapper.vm.login(loginData);
		expect(wrapper.vm.username).toBe("sunshine");
	});
});

结果

不匹配时

image-20230831163309372
image-20230831163309372

匹配时

image-20230831163330050
image-20230831163330050

文档

官方文档:https://jestjs.io/zh-Hans/docs/expectopen in new window

vue-test-utils 文档:https://v1.test-utils.vuejs.org/zh/guides/#起步open in new window

博客:https://blog.csdn.net/lambert00001/article/details/130912370open in new window

Loading...