Tips for using localStorage in vue testing

Currently, I am in the process of testing Vue components for my project.

The component I am working with is a single file Vue component that relies on vuex. The states are stored in store.js, which utilizes localStorage. However, when I execute the command npm test, an error occurs with the following message:

WEBPACK Compiled successfully in 9416ms

MOCHA Testing...

RUNTIME EXCEPTION Exception occurred while loading your tests

ReferenceError: localStorage is not defined

The testing tools that I am utilizing include: @vue/test-utils, expect, jsdom, jsdom-global, mocha, mocha-webpack


The way I run the tests is as follows:

"test": "mocha-webpack --webpack-config node_modules/laravel-mix/setup/webpack.config.js --require tests/JavaScript/setup.js tests/JavaScript/**/*.spec.js"

An example test file named order.spec.js looks like this:

require('../../resources/assets/js/store/store');
require('../../resources/assets/js/app');
import { mount } from '@vue/test-utils';
import Order from '../../resources/assets/js/views/order/List.vue';
import expect from 'expect';

describe('Order', ()=>{
    it('has alert hidden by default', () => {
        let wrapper = mount(Order);
        expect(wrapper.vm.alert).toBe(false);
    })
})

In the setup.js file, I include jsdom using the following code snippet:

require('jsdom-global')();

Now, the question arises how can I resolve this issue?

Answer №1

It has come to our attention that the jsdom-global library is currently utilizing an outdated version of jsdom, despite the fact that jsdom has been supporting localStorage since version 11.12.0.

If you wish to leverage the features of jsdom 11.12 and above with localStorage support, you have the option to manually include jsdom window properties in the global scope within a test setup file that precedes your tests:

/* setup.js */

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
  Object.defineProperties(target, {
    ...Object.getOwnPropertyDescriptors(src),
    ...Object.getOwnPropertyDescriptors(target),
  });
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
global.requestAnimationFrame = function (callback) {
  return setTimeout(callback, 0);
};
global.cancelAnimationFrame = function (id) {
  clearTimeout(id);
};
copyProps(window, global);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating an MD5 hash for a UTF16LE string in Javascript (with no BOM and excluding 0-byte at the end) - Illustrated with a C#

I've been trying to figure out how to get an MD5 Hash of a UTF16-LE encoded string in JavaScript for the past few days. I have a method in C# as an example, but I'm not sure how to replicate it in JavaScript. Example: public string GetMD5Hash ( ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

Stop the body from scrolling when dialog is open on a mobile screen

I am encountering an issue on a mobile screen where I am displaying a dialog that is longer than the screen size, causing it to scroll. The problem arises when scrolling past the bottom of the dialog (I am utilizing Bootstrap 3) as instead of stopping, it ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

"jQuery's toggleClass Method for Efficient Class Swapping

I have been working on a script that is supposed to change the color of a square upon clicking it using the toggleClass() method in jQuery. However, my code seems correct but for some reason, the square's color isn't changing. Can someone help me ...

Enhance User Experience: Implement Asynchronous Loading of Vue Components in Laravel 5.6 using laravel-mix and webpack

Laravel 5.6.21 NPM 6.1.0 Node 10.5.0 Webpack 3.12.0 Seeking guidance on how to correctly set up laravel-mix, webpack, and babel to enable lazy-loading of vue components using the technique outlined in Lazy Loading Routes. In particular, implementing stag ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Incorporating SOAP Service into AngularJS Using AngularJS Data Model

As an experienced Flex Developer diving into the world of AngularJS, I must admit, it's quite confusing!!! Currently, my focus is on making a service call to my backend server (located on the same domain) using a SOAP WSDL Request and populating the ...

What is the best way to pass parameters to a PHP script using AJAX to ensure they are properly processed on the server side?

I'm working with the following function: function myFunction () { $.getJSON('remote.php', function(json) { var messages = json; function check() { ... In this function, I call the remote.php script which e ...

Establishing communication from a node.js application to an Apache server with version 2.2

Each time I call the function dorequest during a request to my node server, I encounter an issue with requests to a webpage hosted on apache2.2.21. While most of the requests are successful, I am getting an error ECONNRESET on a few of them, and I am uns ...

Enhance the functionality of the 'validate as true' function

I have an object that resembles the following $scope.object = { Title: 'A title', Status: 'Open', Responsible: 'John Doe', Author: 'Jane Doe', Description: 'lorem ipsum dolor sit' } My aim now i ...

What is the best method for storing a Google Analytics object in a $_SESSION variable when transitioning between PHP scripts to avoid encountering a non-object error

Currently in the process of developing a web application that integrates with the Google Analytics API, however encountering challenges when it comes to implementation. The user is given the option to choose their profile from three interconnected drop-do ...

Issue with Vuex: token is not being stored in local storage

I have a Vue App store set up with Vuex: import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { email: null, token: localStorage.getItem(&apos ...

The restify.bodyParser() function does not seem to be functioning correctly, as the req object is appearing

When working with restify, I've noticed that the request object is always empty when making HTTP POST calls. Does anyone have any ideas on why this might be happening? Thanks ...

Tips for updating the id of a tag using JavaScript?

Html Code:- {% for post in posts %} <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="{% url 'post-detail' post.slug %}">{{ post.title }}&l ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Access Images from Server using Front-End Technology

I have a collection of images stored in a server folder that I want to display on a div element using client-side code. Initially, I tried to achieve this with AJAX, but it returned raw data instead of the image URL. Despite my efforts to find a solution, ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Is there a method I can use to transform this PHP script so that I can incorporate it in .JS with Ajax?

I have a JavaScript file hosted on domain1.com, but in order for it to function properly, I need to include some PHP code at the beginning. This is necessary to bypass certain restrictions on Safari for my script by creating a session. The PHP code establi ...