I am trying to test an axios request, and I need to use an auth token in order to access the endpoint, however my test fails because I am getting “Bearer null” and inputting this into my headers.Authorization. Here is my actual code below
File I’m testing:
JavaScript
x
25
25
1
this.$axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem("access-token")}` } })
2
.then((response) => {
3
this.loading = true;
4
// Get latest barcode created and default it to our "from" input
5
this.barcodeFrom = response.data.data[response.data.data.length - 1]['i_end_uid'] + 1;
6
this.barcodeTo = this.barcodeFrom + 1;
7
this.barcodeRanges = response.data.data;
8
9
// Here we add to the data array to make printed barcodes more obvious for the user
10
this.barcodeRanges.map(item => item['range'] = `${item['i_start_uid']} - ${item['i_end_uid']}`);
11
12
// Make newest barcodes appear at the top
13
this.barcodeRanges.sort((a, b) => new Date(b['created_at']) - new Date(a['created_at']));
14
})
15
.catch((error) => {
16
console.log('Barcode retrieval error:', error);
17
this.barcodeFrom === 0 ? null : this.snackbarError = true;
18
})
19
.finally(() => {
20
// Edge case when there's no barcode records
21
this.barcodeFrom === 0 ? this.barcodeTo = 1 : null;
22
this.loading = false
23
});
24
console.log('bcr', this.barcodeRanges);
25
Test file:
JavaScript
1
59
59
1
import Vuetify from "vuetify";
2
import Vuex from "vuex";
3
import { createLocalVue, shallowMount } from "@vue/test-utils";
4
import VueMobileDetection from "vue-mobile-detection";
5
import axios from 'axios';
6
7
import index from "@/pages/barcode_logs/index";
8
9
describe('/pages/barcode_logs/index.vue', () => {
10
// Initialize our 3rd party stuff
11
const localVue = createLocalVue();
12
localVue.use(Vuetify);
13
localVue.use(Vuex);
14
localVue.use(axios);
15
localVue.use(VueMobileDetection);
16
17
// Initialize store
18
let store;
19
20
// Create store
21
store = new Vuex.Store({
22
modules: {
23
core: {
24
state: {
25
labgroup:{
26
current: {
27
id: 1
28
}
29
}
30
}
31
}
32
}
33
});
34
35
// Set-up wrapper options
36
const wrapperOptions = {
37
localVue,
38
store,
39
mocks: {
40
$axios: {
41
get: jest.fn(() => Promise.resolve({ data: {} }))
42
}
43
}
44
};
45
46
// Prep spies for our component methods we want to validate
47
const spycreateBarcodes = jest.spyOn(index.methods, 'createBarcodes');
48
const createdHook = jest.spyOn(index, 'created');
49
// Mount the component we're testing
50
const wrapper = shallowMount(index, wrapperOptions);
51
52
test('if barcode logs were retrieved', () => {
53
expect(createdHook).toHaveBeenCalled();
54
expect(wrapper.vm.barcodeRanges).toHaveLength(11);
55
});
56
57
});
58
59
How do I mock or get the actual auth token in to work in my test?
Advertisement
Answer
You can try to mock localStorage
before creating instance of a wrapper like this:
JavaScript
1
12
12
1
global.localStorage = {
2
state: {
3
'access-token': 'superHashedString'
4
},
5
setItem (key, item) {
6
this.state[key] = item
7
},
8
getItem (key) {
9
return this.state[key]
10
}
11
}
12
You can also spy on localStorage
functions to check what arguments they were called with:
JavaScript
1
3
1
jest.spyOn(global.localStorage, 'setItem')
2
jest.spyOn(global.localStorage, 'getItem')
3
OR
You can delete localVue.use(axios)
to let your $axios
mock work correctly.
This
JavaScript
1
6
1
mocks: {
2
$axios: {
3
get: jest.fn(() => Promise.resolve({ data: {} }))
4
}
5
}
6
is not working because of that
JavaScript
1
2
1
localVue.use(axios)
2