Vue-test-utils encounters a `SyntaxError` when importing with Jest, throwing the error message "Cannot use import statement outside a module"

I'm facing an issue with my NuxtJS setup using Jest and Typescript. I can't seem to get my test to run properly due to an exception.

 Details:

    /home/xetra11/development/myapp/test/Navigation.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { mount } from '@vue/test-utils';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

My unit test is simple:

import { mount } from '@vue/test-utils'
import Navigation from '@/components/layout/Navigation.vue'

describe('navigation', () => {
  test('is correct', () => {
    const wrapper = mount(Navigation)
    expect(wrapper.vm).toBeTruthy()
  })
})

Below is my jest.config.js. I've included transformIgnorePatterns based on suggestions I found online:

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js'
  },
  moduleFileExtensions: [
    'ts',
    'js',
    'vue',
    'json'
  ],
  transform: {
    "^.+\\.ts$": "ts-jest",
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  transformIgnorePatterns: [
    "node_modules/@vue/test-utils/dist/vue-test-utils.js",
  ],
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue'
  ]
}

Here's a snippet from my package.json:

 "devDependencies": {
    "@nuxt/types": "^2.15.3",
    "@nuxt/typescript-build": "^2.1.0",
    "@nuxtjs/vuetify": "^1.11.3",
    "@vue/test-utils": "^1.1.3",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^26.6.3",
    "jest": "^26.6.3",
    "ts-jest": "^26.5.4",
    "vue-jest": "^3.0.4"
  }

Any insights on what might be causing this problem?

Answer №1

I encountered a similar issue that I was able to resolve by installing babel-core bridge:

npm install --save-dev babel-core@^7.0.0-bridge.0

In addition, I also needed to include the following code snippet in jest.config.js:

  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },

Check out the documentation for more information.

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

Enhance your Vue 3 experience by optimizing URL parameters for easy bookmarking and efficient filtering

I am eager to enhance my application by adding URL parameter functionality: When a filter is applied, the URL should be updated automatically If someone accesses the URL directly, they should see the same filtered data I have observed various approaches ...

Following the completion of the inspection, the next step

Check out my work at this link: Unfortunately, my code is too lengthy to include here, so please refer to the link above to see the issue I am facing. The problem I am encountering is that when I click the checkbox after adding an item to the list, the r ...

Is there a way to adjust the height pixel value in my code so it can be dynamic?

I have created a simple script that allows selected objects to fade in as the user scrolls down. However, my issue is that this script is quite rigid. If I were to apply it to 20 different objects, for example, I would need to manually adjust the height ea ...

Transform the jQuery Mobile slider into a jQuery UI slider and update the text

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> function modifycontent() { if (document.getElementById("slider").value<33) { $("#1").fadeIn("slow"); $("#2").fadeOut("slow"); ...

The Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...

An error has occurred as ByChained is not recognized

Recently, I have been experimenting with selenium webdriverjs in javascript to locate an element that includes the partial text "hoi" as well as the text "hoe gaat het". I attempted to use ByChained for this purpose, but encountered an error stating that ...

What is causing the recurring failure of file input changes to take effect?

Here is the code snippet I'm working with: <input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" /> Along with the handler function: public onFileSelected(e: Fi ...

Deleting a user in Vue.js using Firebase UID

I'm working on implementing a function in my Vue.js Firebase application that allows users to be deleted by UID. The app is designed to allow user registration through email and password authentication in Firebase. Once a user is logged in, they shoul ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Save the chosen information into the database

My goal is to insert a Foreign key, acc_id, into the patient_info table from the account_info table. I have successfully retrieved the data from my database and now I want to use it as a Foreign key in another table. Here is the code snippet: try { $ ...

What is the significance of utilizing `.value` within a template when working with a function that produces a computed ref?

One of my functions returns a ComputedRef as shown below: // The computed ref function const publishedBooksMessage = () => computed(() => { return books.length > 0 ? 'Yes' : 'No' }) In order to access the value returned by t ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

How to Trigger a Javascript Function from a Wordpress Navigation Menu

On my website developed in HTML, I have the ability to invoke any JavaScript function using an anchor tag like this <a href="javascript:function();"></a> However, when attempting to add this to a WordPress menu option and saving the menu, eve ...

Using Three.js to load an image from a different domain

Despite searching extensively and reading through all available resources, I am unable to find a solution to my issue. I am currently running this code on a local server (IIS). My objective is to load an image from imgur and utilize it as a texture for an ...

Tips for closing the stdio pipes of child processes in node.js?

Looking to spawn a child process from node.js and monitor its stdout before closing the pipe to terminate the node process. Here's my base code snippet that is currently not ending the node process: const childProcess = require("child_process"); con ...

When attempting to call a Firebase Cloud Function URL in an AngularJS $http request, an Access Control Origin Error

I recently created a cloud function that involves linking with Plaid. I'm currently working on calling this function using AngularJS's $http method. While the cloud function code is being executed, I encountered an error in my console instead of ...

Retrieving the $vuetify instance property within the vuex store

While using vuetify, I tried to change the theme from the vuex store using the $vuetify instance, but encountered the following error: Cannot set property 'theme' of undefined Below is the code snippet: export default { getters: {}, mutatio ...

"Update content dynamically with PHP-AJAX only when there are

Hey there, I've got a comment system that's being constantly updated with jQuery. My goal is to only refresh it when new records are added to the database. Is this possible? Please forgive any mistakes in my English, as I'm using Google Tra ...

Nuxt | Sometimes HTML tags are only visible inside JavaScript tags when viewing the source code in a browser

Upon visiting the following page and right clicking to select "View page source", you may notice that the text "100s Man With Van Providers" is located within <script type="text/javascript"> instead of an HTML tag. These scripts are transmitted fro ...

What is the best way to divide an array of objects into three separate parts using JavaScript?

I am looking to arrange an array of objects in a specific order: The first set should include objects where the favorites array contains only one item. The second set should display objects where the favorites array is either undefined or empty. The third ...