Attempting to import a module that has already been imported will result in a ReferenceError

As a JavaScript newbie tasked with maintaining a large application, I recently implemented a new feature that passed manual testing successfully in both development and production modes. However, when running tests using vue-cli-service test:unit (mocha + chai), I encountered a runtime exception:

Exception occurred while loading your tests`
ReferenceError: Cannot access 'serviceBase' before initialization

The issue seems to stem from the serviceBase.json file:

import api from "./api";
import store from "./../store";
import i18n from "../../plugins/i18n";

export const serviceBase = {
  api: api,
  resource: "",
  preList: "me",
  preListOption: {
    getList: true
  },
{.....}

This serviceBase is utilized in various areas, including the documentImageService.js file:

import { createErrorMessage, serviceBase, clearance } from "../service";
import api from "../api";
import axios from "axios";

const DocumentImage = {
  ...serviceBase,
  clearance,
{.....}

The DocumentImage constant is then imported in the renderer.js file:

import * as HB from "handlebars";
import { Helpers } from "@lextira/lexgate-document-renderer";
import DocumentImage from "@/store/utils/services/documentImageService.js";

export default class {
  /** @type {HB} */
  handlebars = undefined;
  /** @type {string} */
  clearanceToken = undefined;
{.....}

Removing the import of DocumentImage allows the tests to run without issues, indicating that the test runtime is being affected. While the feature works fine in the browser runtime, the test environment seems to be reacting differently.

I suspect the problem lies in the mocha runtime configuration, but I haven't found any relevant information in the current documentation to address this issue.

Answer №1

Eventually, it was discovered that there was a circular dependency causing issues, despite my skepticism for most of the time.

DocumentImageStoreDocumentImageServiceServiceBaseNotificationStore.

Since both DocumentImageStore and NotificationStore originate from the same vuex-store, there are instances where the dependency is not resolved, while in other cases it is (potentially based on the order of requests).

To address this, I implemented a lazy import for the NotificationStore in the Service:

const getStore = () => import("./../store");

export const createNotification = function(message) {
  getStore().then(store => {
    store.default.dispatch("notificationStore/createNotification", message)
  });
}

Ideally, the best solution would be to fully resolve the circular dependency. However, given the current implementation, I am unsure of the best approach to achieve this.

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

The data displayed in the <span> element isn't reflecting the response from the loaded page, despite being visible in Firebug

I have encountered a problem while trying to load a signup.php page into a div on my main page. All the elements (forms, JavaScript, etc.) function correctly in the loaded page, except for one issue - I cannot get the response from the PHP script to displa ...

Attempting to retrieve assets from an incorrect directory in a rush

Within my express project, I have encountered an issue when rendering the product route with a specific id. It seems that the assets are attempting to load from /products in the public folder (even though this directory does not exist). However, when I ren ...

Angular 6 is throwing an error stating that the element 'app-action-button' is not recognized

I'm facing an issue while trying to incorporate a component that is shared between modules. Unfortunately, all my attempts have resulted in the same error. Despite searching for solutions in similar questions, I have been unable to resolve this error ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...

Having trouble navigating to the link using Selenium WebDriver

I encountered an issue when trying to click on a link as it displayed an "Element Not Found" message. Below is the HTML code I used: <a id="expTo" class="formblue_link padRight10 exportLinkActive" style="display: block; margin-left: -50px; margin-b ...

Breaking apart a string and mapping it to specific fields

My issue is relatively straightforward. Upon loading my page, a long string representing an address is generated. For example: 101, Dalmations Avenue, Miami, Florida, USA, 908343 With the help of jQuery, I can split the string using: var address = sel.o ...

Updating an HTML element in Django using JavaScript and Ajax: A Step-by-Step Guide

I am attempting to modify an html element on a webpage using javascript. Everything works perfectly when the home page initially loads, but when I click on the New Product link, only the context string is displayed on the home page. html <!-- product/ ...

Tips on handling a JSON string alert

Can someone guide me on how to extract a specific value from a JSON string I received in an alert message? The JSON string looks like this: {"Error":true, "data":["not available","somethinghere"]} The JSON string is obtained from an alert using the follow ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Implementing Scroll-Activated Class with Vanilla JavaScript

I'm currently developing a Vue.js project and I want to implement a feature where a "back to top" button appears when the user scrolls beyond a certain point. However, I'm encountering an issue without using JQuery. Can you help me troubleshoot t ...

What is the best way to increase a numerical input?

While experimenting with HTML input elements, I decided to utilize the step attribute. This allowed me to increment the current value by 100 when clicking the up or down arrows in the input field. However, I discovered that the step attribute restricts th ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Helpful tips for resolving the issue of avoiding prop mutation in Vue

I encountered an issue in my console [Vue warn]: I received a warning message about mutating a prop directly, which can lead to the value being overwritten whenever the parent component re-renders. It is recommended to use a data or computed property bas ...

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

What is the method for incorporating an onmouseover event into child states while extending the parent state controller?

I have a basic angularjs controller coupled with jquery that triggers a console log message when the mouse hovers over an anchor element: app.controller('MenuController', function() { $("a").on('mouseover', function (e) { c ...

How can Vue.js leverage dynamic templates within a component?

const CustomComponent = { props: ['index'], template: `<span>I am a custom component: {{ index }}</span>` }; const UserInputResult = { components: { CustomComponent }, props: ['templateString'], template: `& ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Retrieve index by clicking on a mapped array in a React.js application

class DataCard extends React.Component { constructor(props){ super(props) this.state = { show: false, } } displayContent = (e) => { e.preventDefault(); console.log(e.target.entry); } render() { console.log(this.props ...