Vue JS - Unit test - localstorage is not defined
Asked Answered
I

2

7

I'm writing unit test for for vue cli 3 using Mocha and chai. I have tried mocking localstorage. but still getting this error - 'localStorage is not defined'. Can anyone please help me here?

My code is like this -

import { expect, assert } from 'chai';
import { shallowMount } from '@vue/test-utils';
import LoginComponent from '@/views/LoginComponent.vue';
import Constants from '@/constants';

declare var global: any;
let wrapper;
let componentInstance: any;
let authData;
var mockLocalStorage = {
  getItem(key: any) {
    if (key === 'access_token') { return '/* a token object */'; }
    return 'null';
  }
};

describe('LoginComponent.vue', () => {
  beforeEach(() => {
    global.window = { localStorage: mockLocalStorage };

    authData = JSON.stringify(Constants.AUTH_DATA);

    wrapper = shallowMount(AliUMSLoginComponent, {
      propsData: { authData }
    });
    componentInstance = wrapper.vm;
  });

  it('has a created hook', () => {
    assert.isNotNull(componentInstance.authData);
  });
});
Innermost answered 28/2, 2019 at 9:43 Comment(0)
H
4

For anyone else who might stumble upon this question - the following worked for me:

1) Create a setup.js file in your unit test folder and add the following code:

require('jsdom-global')();

global.localStorage = window.localStorage;

After fixing the "localStorage is undefined" error, you might experience additional errors (like I did). In the end the following code snippet fixed everything:

require('jsdom-global')(undefined, { url: 'https://localhost' });

global.localStorage = window.localStorage;
global.sessionStorage = window.sessionStorage;
window.Date = Date;

... You can find more info on this here: vuejs/vue-cli/issues/2128 and here: vuejs/vue-test-utils/issues/936

2) Update the test script in your package.json file to load the setup file you just created:

"test:unit": "vue-cli-service test:unit --require tests/unit/setup.js"

Hohenzollern answered 7/12, 2019 at 6:21 Comment(0)
G
1

I got your solution to work however when trying to grep for one file to run, it runs all files.

  1. Is there a better way to include this maybe with an include at the top of the file? An include usually has a method that returns something. hmmmm how to do this?

  2. Is this the correct syntax for the package.json file:

"test:unit-filter": "vue-cli-service test:unit --require tests/unit/helpers/setup.js --watch --grep"
Guadalcanal answered 9/11, 2022 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.