Javascript 使用Vue和Jest/Vue测试utils模拟API调用
我使用Vue作为前端,使用Python/Django作为后端。我希望编写测试以确保对后端的API调用按预期工作,但我在模拟Axios调用时遇到了困难 我可能设置错误,但您可以看到,我有一个函数,该函数将在组件“创建”挂钩内调用。因此,在创建组件时,此函数将调用我的后端,以根据URL附带的查询参数检索信息。这一切都是可行的,但我想学习如何模拟这个API请求来编写更好的测试 API服务这在整个应用程序中用于调用后端 文件路径:src/api/api.jsJavascript 使用Vue和Jest/Vue测试utils模拟API调用,javascript,vue.js,jestjs,axios,Javascript,Vue.js,Jestjs,Axios,我使用Vue作为前端,使用Python/Django作为后端。我希望编写测试以确保对后端的API调用按预期工作,但我在模拟Axios调用时遇到了困难 我可能设置错误,但您可以看到,我有一个函数,该函数将在组件“创建”挂钩内调用。因此,在创建组件时,此函数将调用我的后端,以根据URL附带的查询参数检索信息。这一切都是可行的,但我想学习如何模拟这个API请求来编写更好的测试 API服务这在整个应用程序中用于调用后端 文件路径:src/api/api.js import axios from "axi
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>
尝试模拟API?
文件路径:src/api/mocks/api.js
假设business_list.json是来自API的json响应示例
[
{
"id": 90,
"user": 67
},
{
"id": 89,
"user": 67
}
]
您可以使用来轻松模拟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();
})
import businessList from "./data/business_list.json";
export default {
get: () => Promise.resolve({ data: businessList })
};
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();
})