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

标签 javascript jestjs nuxt.js vue-test-utils

我正在尝试测试 axios 请求,并且我需要使用身份验证 token 才能访问端点,但是我的测试失败,因为我得到“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);
    });

});

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

最佳答案

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

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

关于javascript - 如何访问 localStorage 或模拟 localStorage 以进行 Jest + vue-test-utils 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67644948/

相关文章:

javascript - 使用 Javascript 编辑打开的 HTML 页面

javascript - 如何在nuxt中使用amchart?

vue.js - 使用 Nuxt 拦截 apollo-module 上的网络错误

javascript - 我可以改进这个 AngularJS/AJAX javascript 片段吗?

javascript - jQuery:验证错误后,我的输入掩码功能在现场不起作用

jestjs - 避免有条件地调用 `expect` : jest testing error

javascript - 如何修复在使用 Jest 进行测试时未正确检查 ajv 模式

reactjs - 使用 react-testing-library 测试导航

vue.js - 基于路由的条件状态

javascript - jQuery .when() .then() promise 不遵守 for 循环