Utilizing Vue for the frontend and Python/Django for the backend, I aim to create tests that verify the functionality of my API calls. However, I am encountering difficulties when attempting to mock out the Axios calls.
I suspect there might be an issue with how I have set this up. I have a function designed to be called within the component's "created" hook. This function is responsible for making a call to the backend to fetch information based on the query parameter from the URL. While it currently works as intended, I seek to understand how to mock this API request in order to enhance my testing process.
API Service: This service is used across the application to interact with the backend.
File Path: 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}`
}
});
Single File Component:
The following code snippet functions correctly:
<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 file path: 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();
});
});
Attempted mock API? file-path: src/api/mocks/api.js
Assume business_list.json represents a sample JSON response from the API.
[
{
"id": 90,
"user": 67
},
{
"id": 89,
"user": 67
}
]
import businessList from "./data/business_list.json";
export default {
get: () => Promise.resolve({ data: businessList })
};