Skip to content
Advertisement

How do I access localStorage or mock localStorage for Jest + vue-test-utils tests?

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:

this.$axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem("access-token")}` } })
            .then((response) => {
                this.loading = true;             
                // Get latest barcode created and default it to our "from" input
                this.barcodeFrom = response.data.data[response.data.data.length - 1]['i_end_uid'] + 1;
                this.barcodeTo = this.barcodeFrom + 1;
                this.barcodeRanges = response.data.data;

                // Here we add to the data array to make printed barcodes more obvious for the user
                this.barcodeRanges.map(item => item['range'] = `${item['i_start_uid']} - ${item['i_end_uid']}`);

                // Make newest barcodes appear at the top
                this.barcodeRanges.sort((a, b) => new Date(b['created_at']) - new Date(a['created_at']));
            })
            .catch((error) => {
                console.log('Barcode retrieval error:', error);
                this.barcodeFrom === 0 ? null : this.snackbarError = true;
            })
            .finally(() => {
                // Edge case when there's no barcode records
                this.barcodeFrom === 0 ? this.barcodeTo = 1 : null;
                this.loading = false
            });
            console.log('bcr', this.barcodeRanges);

Test file:

import Vuetify from "vuetify";
import Vuex from "vuex";
import { createLocalVue, shallowMount } from "@vue/test-utils";
import VueMobileDetection from "vue-mobile-detection";
import axios from 'axios';

import index from "@/pages/barcode_logs/index";

describe('/pages/barcode_logs/index.vue', () => {
    // Initialize our 3rd party stuff
    const localVue = createLocalVue();
    localVue.use(Vuetify);
    localVue.use(Vuex);
    localVue.use(axios);
    localVue.use(VueMobileDetection);

    // Initialize store
    let store;

    // Create store
    store = new Vuex.Store({
        modules: {
            core: {
                state: {
                    labgroup:{
                        current: {
                            id: 1
                        }
                    }
                }
            }
        }
    });

    // Set-up wrapper options
    const wrapperOptions = {
        localVue,
        store,
        mocks: {
            $axios: {
                get: jest.fn(() => Promise.resolve({ data: {} }))
            }
        }
    };

    // Prep spies for our component methods we want to validate
    const spycreateBarcodes = jest.spyOn(index.methods, 'createBarcodes');
    const createdHook = jest.spyOn(index, 'created');
    // Mount the component we're testing
    const wrapper = shallowMount(index, wrapperOptions);

    test('if barcode logs were retrieved', () => {
        expect(createdHook).toHaveBeenCalled();
        expect(wrapper.vm.barcodeRanges).toHaveLength(11);
    });

});

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:

global.localStorage = {
  state: {
    'access-token': 'superHashedString'
  },
  setItem (key, item) {
    this.state[key] = item
  },
  getItem (key) { 
    return this.state[key]
  }
}

You can also spy on localStorage functions to check what arguments they were called with:

jest.spyOn(global.localStorage, 'setItem')
jest.spyOn(global.localStorage, 'getItem')

OR

You can delete localVue.use(axios) to let your $axios mock work correctly.

This

mocks: {
  $axios: {
     get: jest.fn(() => Promise.resolve({ data: {} }))
  }
}

is not working because of that

localVue.use(axios)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement