I'm using Vue for the frontend and Python/Django for the backend. I would like to write tests to ensure that my API calls to my backend are working as expected but I'm having trouble mocking out the Axios calls.
I'm probably set this up wrong but you can see that I have one function that is meant to be called inside of the components "created" hook. Thus when the component is created this function makes a call to my backend to retrieve information based on the query parameter that comes with the URL. This all works but I want to learn how to mock this API request to write better tests.
API Service This is used throughout the app to call 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
This does work:
<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 is an example 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 })
};