远程接口请求测试组件(RemoteApiTest.vue)
vue
<template>
<button @click="fetchResults">{{ value }}</button>
</template>
<script>
// import { getBtnText } from "@/api/insure/index.simple.js"; //
export default {
data() {
return {
value: "点击",
};
},
methods: {
async fetchResults() {
// const response = await getBtnText();
// this.value = response.data;
},
},
};
</script>远程接口请求测试(RemoteApiTest.spec.js)
js
// src/components/__tests__/RemoteApiTest.spec.js
import { shallowMount } from "@vue/test-utils";
import flushPromises from "flush-promises";
// import axios from "axios";
import RemoteApiTest from "../JestTest/RemoteApiTest.vue";
/**
* 测试组件 RemoteApiTest 中的真实接口请求
*/
describe("RemoteApiTest", () => {
/**
* 真实接口请求:点击按钮后获取数据并渲染
*/
it("真实接口请求:点击按钮后获取数据并渲染", async () => {
// 1. 挂载组件
const wrapper = shallowMount(RemoteApiTest);
// 2. 记录初始文本(确保初始状态正确)
const initialText = wrapper.text();
expect(initialText).toBe("点击"); // 假设初始文本为空
// 3. 点击按钮触发真实接口请求
await wrapper.find("button").trigger("click");
// 4. 等待真实接口响应(关键:根据接口延迟调整等待逻辑)
// 循环等待,直到数据渲染或超时(最多等10秒)
let waitTime = 0;
while (wrapper.text() === initialText && waitTime < 100) {
await new Promise((resolve) => setTimeout(resolve, 100)); // 每100ms检查一次
waitTime++;
}
// 关键:使用 flushPromises 确保所有 Promise 都已 resolve
// await flushPromises();
// 5. 断言接口返回的数据已渲染(根据真实接口返回值调整)
expect(wrapper.text()).toContain("更新后按钮文本"); // 用 toContain 兼容可能的其他文本
});
});