【问题标题】:How do I access localStorage or mock localStorage for Jest + vue-test-utils tests?如何访问 localStorage 或模拟 localStorage 以进行 Jest + vue-test-utils 测试?
【发布时间】:2021-08-11 03:47:23
【问题描述】:

我正在尝试测试 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);
    });

});

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

【问题讨论】:

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


    【解决方案1】:
    const setItem = jest.spyOn(Storage.prototype, 'setItem')
    const getItem = jest.spyOn(Storage.prototype, 'getItem')
    
    expect(setItem).toHaveBeenCalled()
    expect(getItem).toHaveBeenCalled()
    

    【讨论】:

      【解决方案2】:

      您可以在创建这样的包装器实例之前尝试模拟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)
      

      【讨论】:

      • 在安装我的组件之前,我必须手动 localStorage.setItem('access-token') = 'mytoken',但是您的回答将我引向了那个方向,所以谢谢。不过,我还有另一个问题,当我使用“get: jest.fn(() => Promise.resolve({ data: {} }))”设置 $axios 模拟时,它总是只返回那个空对象“{} ",我是否必须为我模拟 GET 的每个测试硬编码我的预期响应????
      • 很高兴我的代码有帮助!关于 axios 数据:如果您打算在进一步的测试中使用获取的(模拟)数据,那么 $axios.get 应该返回一些数据。
      猜你喜欢
      • 1970-01-01
      • 2018-04-29
      • 2018-09-01
      • 2020-06-08
      • 2019-08-07
      • 2018-12-28
      • 2020-02-13
      • 2019-09-26
      • 1970-01-01
      相关资源
      最近更新 更多