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

myn*_*101 5 javascript jestjs nuxt.js vue-test-utils

我正在尝试测试 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);
Run Code Online (Sandbox Code Playgroud)

测试文件:

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

});

Run Code Online (Sandbox Code Playgroud)

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

小智 11

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

expect(setItem).toHaveBeenCalled()
expect(getItem).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)


Edu*_*rdo 5

localStorage您可以在创建包装器实例之前尝试进行模拟,如下所示:

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

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

jest.spyOn(global.localStorage, 'setItem')
jest.spyOn(global.localStorage, 'getItem')
Run Code Online (Sandbox Code Playgroud)

或者

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

mocks: {
  $axios: {
     get: jest.fn(() => Promise.resolve({ data: {} }))
  }
}
Run Code Online (Sandbox Code Playgroud)

因此无法工作

localVue.use(axios)
Run Code Online (Sandbox Code Playgroud)