gpt4 book ai didi

javascript - 使用 Vue 和 Jest/Vue 测试工具模拟 API 调用

转载 作者:行者123 更新时间:2023-12-01 00:28:21 25 4
gpt4 key购买 nike

我使用 Vue 作为前端,使用 Python/Django 作为后端。我想编写测试来确保对后端的 API 调用按预期工作,但我在模拟 Axios 调用时遇到了困难。

我可能设置错误,但你可以看到我有一个函数,该函数应该在组件“created”钩子(Hook)内部调用。因此,当创建组件时,此函数会调用我的后端,以根据 URL 附带的查询参数检索信息。这一切都有效,但我想学习如何模拟此 API 请求以编写更好的测试。

API 服务这在整个应用程序中用于调用后端。

文件路径:src/api/api.js

import axios from "axios";
import { djangoServiceUser } from "../../config.js";

export default axios.create({
baseURL: "/api",
timeout: 5000,
headers: {
"Content-Type": "application/json",
Authorization: `Token ${djangoServiceUser}`
}
});

单个文件组件

这确实有效:

<script>
import api from "@/api/api";

export default {
data() {
return {
loading: false,
userBusinessOptions: null
};
},
methods: {
fetchBusinesses(fwt_user_id) {
this.loading = true;

api.get(`companies/${fwt_user_id}`).then(
response => {
this.loading = false;
let businessNames = [];
for (let i in response.data) {
businessNames.push(response.data[i].name);
}
this.userBusinessOptions = businessNames;
},
error => {
this.loading = false;
}
);
}
},
created() {
this.fetchBusinesses(this.$route.query.fwt_user_id);
}
};
</script>

beginApplicationVueTest.test.js文件路径:src/views/tests/beginApplicationVueTest.test.js

import { shallowMount } from "@vue/test-utils";
import BeginApplication from "@/views/BeginApplication.vue";
import Vuetify from "vuetify";
import Vue from "vue";
import api from "@/api/__mocks__/api";

Vue.use(Vuetify);

it("fetches businessses", () => {
const $route = {
query: { fwt_user_id: 35 }
};
const wrapper = shallowMount(BeginApplication, {
mocks: {
$route
}
});
expect(wrapper.vm.$route.query.fwt_user_id).toBe(35);

wrapper.vm.fetchBusinesses(wrapper.vm.$route.query.fwt_user_id);
wrapper.vm.$nextTick(() => {
expect(wrapper.vm.userBusinessOptions).toBe("test");
done();
});
});

尝试模拟 API?文件路径:src/api/mocks/api.js

假设business_list.json是来自API的示例JSON响应。

[
{
"id": 90,
"user": 67
},
{
"id": 89,
"user": 67
}
]
import businessList from "./data/business_list.json";

export default {
get: () => Promise.resolve({ data: businessList })
};

最佳答案

您可以使用Moxios轻松模拟 Axios http 调用。对于您的用例,您可以执行以下操作:

import moxios from 'moxios'; // you have to npm install moxios
import api from './path/to/api.js';
import businessList from './path/to/business_list.json';

it('...', () => {
// Install the axios instance the api module is exporting
moxios.install(api);

moxios.stubRequest(new RegExp('.*?/api/comapines.*'), {
status: 200,
response: { data: businessList }
});


// Test body...
// Any axios call to an endpiont that matches the regExp would always return the response specified

moxios.uninstall();
})

关于javascript - 使用 Vue 和 Jest/Vue 测试工具模拟 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com