Issue: Unable to utilize import statement outside a module as per the guidelines of the vue-test-utils official tutorial

I'm struggling to get Vue testing set up with vue-test-utils and jest. I followed the installation guide at https://vue-test-utils.vuejs.org/installation/#semantic-versioning, but can't seem to figure out what's wrong. Here's what I've done so far:

  1. vue create jest-test

    1.1. npm install

  2. npm install --save-dev jest @vue/test-utils vue-jest

  3. Added jest config to package.json:

    {
      "jest": {
        "moduleFileExtensions": [
          "js",
          "json",
          "vue"
        ],
        "transform": {
          ".*\\.(vue)$": "vue-jest"
        }
      }
    }
    
  4. npm install --save-dev babel-jest @babel/core @babel/preset-env babel-core@^7.0.0-bridge.0

  5. Adjusted jest config to:

    {
      "jest": {
        "transform": {
          // process `*.js` files with `babel-jest`
          ".*\\.(js)$": "babel-jest" 
        }
      }
    }
    
    1. Adjusted babel config to:
    module.exports = {
        presets: [
            '@vue/cli-plugin-babel/preset',
            '@babel/preset-env' 
        ]
    };
    
  6. Created example.test.js in a tests directory under the project root (jest-test/tests)

  7. Added the following to this file:

    import { mount } from '@vue/test-utils'
    import HelloWorld from "@/components/HelloWorld";
    
    
    test('displays message', () => {
        const wrapper = mount(HelloWorld)
    
        expect(wrapper.text()).toContain('Welcome to Your Vue.js App')
    })
    
  8. Added the following to the package.json scripts:

    "jest": "jest"

  9. npm run jest

  10. Encountering the error:

    C:\Users\xxx\jest-test\tests\example.test.js:1
        import { mount } from '@vue/test-utils'
        ^^^^^^
    
        SyntaxError: Cannot use import statement outside a module
    

I face the same issue with Mocha or when attempting it on an existing project. Is there a bug here? I'm at a loss, any help would be appreciated.

Edit: It seems to work fine when using Vue CLI https://vue-test-utils.vuejs.org/installation/#installation-with-vue-cli-recommended

Answer №1

In order to successfully run your tests, it is important to transform both *.vue and *.js files. I attempted to replicate the issue using your configuration, but upon making adjustments to the jest.config.js as shown below, the tests executed without any problems:

module.exports = {
  "moduleFileExtensions": [
    "js",
    "json",
    "vue"
  ],
  transform: {
    '.*\\.js$':'babel-jest',
    ".*\\.(vue)$": "vue-jest"
  },
  moduleNameMapper: {
    "@/(.*)": "<rootDir>/src/$1",
  },
  testEnvironment: 'jsdom'
}

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 concept of asynchronicity and callbacks in JavaScript

As a newcomer to the world of JavaScript and Stack Overflow, I have been learning about synchronous, asynchronous, and callbacks through various videos and blogs. However, I still have a lingering doubt. If synchronous code means following a sequential ord ...

Execute a function singularly upon vertical scrolling upwards or downwards

Looking for a solution to load two distinct animated graphics on a website when scrolling up or down, I managed to trigger the desired functions. However, there seems to be a bug where the functions are being triggered excessively: $(window).scroll(func ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error: Uncaught TypeError: Cannot read property 'unshift' of u ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

Avoid using references when removing elements from an array in JavaScript

For a straightforward logging system, I've devised a method of storing arrays as log entries within a single array. Here's how the code functions: var myarr = new Array(); var secondarr = new Array(4,5,6); myarr.push(secondarr); secondarr.length ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

Encountering the error code [$injector:unpr] regarding an unknown provider: $uibModalInstanceProvider

In my web application, I have a controller called AddPrice. This controller is invoked from a Price listing screen as a popup using the $uibModal.open method, where the controller is passed in as an argument. However, the controller is not defined within t ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

Ways to resolve Error: Project needs yarn, but it is not currently installed

Just finished setting up my new project using the following commands: npm install --global yarn vue create elecprog yarn serve (-> encountered an error) Running everything through VS Code terminal. PS D:\elcp\elecprog> yarn serve yarn run ...

Methods for concealing a single item in a Vue web form

I am a beginner with Vue and I am facing a challenge in hiding a specific element within a web form that is part of a loop. I am trying to use v-if along with a showHideEditComponent method call. However, when I invoke the showHideEditComponent method wi ...

Utilizing a Vue2 component within a Vite/Vue3 application

Currently, I am utilizing Vite/Vue3 with TypeScript and I have a desire to incorporate the Vue2 component found at: https://github.com/tylerkrupicka/vue-json-component Upon importing it using the following statement: import JSONView from 'vue-json-co ...

Verify whether the element in the DOM is a checkbox

What is the method to determine whether a specific DOM element is a checkbox? Situation: In a collection of dynamically assigned textboxes and checkboxes, I am unable to differentiate between them based on their type. ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

Struggling to delete a table row using jquery

Currently, I am encountering an issue with removing a specific "tr" element within a table using jQuery. Here's the situation: I have a table where rows are clickable. Upon clicking on a row, I can update the data associated with that particular obj ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

The Proper Way to Include External CSS in a Next.js Page Without Triggering Any Warnings

I find myself in a scenario where I must dynamically inject CSS into a webpage. The content of this page is constantly changing, and I am provided with raw HTML and a link to a CSS file from a server that needs to be displayed on the page. My attempt to ...