如何访问 localStorage 或模拟 localStorage 以进行 Jest + vue-test-utils 测试?

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

我正在尝试测试 axios 请求,我需要使用身份验证令牌才能访问端点,但是我的测试失败了,因为我收到“Bearer null”并将其输入我的 headers.Authorization.下面是我的实际代码

我正在测试的文件:

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);

测试文件:

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);
    });

});

我如何模拟或获取实际的身份验证令牌以在我的测试中工作?

您可以在创建包装器实例之前尝试模拟 localStorage

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

您还可以监视 localStorage 函数以检查调用时使用的参数:

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

您可以删除 localVue.use(axios) 让您的 $axios 模拟正常工作。

这个

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

因此无法正常工作

localVue.use(axios)
const setItem = jest.spyOn(Storage.prototype, 'setItem')
const getItem = jest.spyOn(Storage.prototype, 'getItem')

expect(setItem).toHaveBeenCalled()
expect(getItem).toHaveBeenCalled()