Using Jest or Mocha alongside Vue: Uncaught SyntaxError: Cannot use import statement outside a module

Update: This post has undergone multiple edits, please refer to this new Stackoverflow post for a clearer explanation of the issue: SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial

I have been searching through countless posts and threads but still can't resolve my problem. I followed the "Getting started" sections of both Jest and Mocha tutorials and encountered the same error each time:

SyntaxError: Cannot use import statement outside a module
. The provided link did not offer a solution.

At the end of this post, you will find steps for setting up a clean project with Jest for testing which unfortunately resulted in an error.

"vue-jest": "^3.0.7"
,
"vue": "^2.6.12"
,
"@vue/test-utils": "^1.2.2"

package.json

"mocha": "mocha 'tests/Frontend/**/*.test.js'"

example.test.js:

import { mount } from "@vue/test-utils"
import Dashboard from "../../resources/js/views/Dashboard";
import * as assert from "assert";

describe('test example', () => {
    it('should work', () => {
        assert.equal([1, 2, 3].indexOf(4), -1); // doesn't matter what I do here
    })
})

What I've attempted:

  • Using the --require @babel/register flag with mocha
  • Setting
    "transformIgnorePatterns": []
    to allow all node_modules to be considered
  • Adding a .babelrc file with specified content, resulting in an error during app build:
Error: Multiple configuration files found. Please remove one:
 - package.json
 - C:\Users\f.marchi\workspace\projects\sanctum-test\.babelrc
{
    "env": {
        "test": {
            "plugins": ["transform-es2015-modules-commonjs"]
        }
    }
}

Do the documentation miss crucial details? I am unsure of where I could be going wrong as I am strictly following the guidelines.

Update: jest.config.js:

module.exports = {
    clearMocks: true,

    collectCoverage: true,

    coverageDirectory: "coverage",

    moduleFileExtensions: [
        "js",
        "json",
        "vue"
    ],
    transform: {
        ".*\\.(vue)$": "vue-jest"
    },
    transformIgnorePatterns: []
};

Update: I have retried the setup process, feel free to follow along:

  1. vue create jest-test
  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"
    }
  }
}
  1. npm install --save-dev babel-jest @babel/core @babel/preset-env babel-core@^7.0.0-bridge.0
  2. Adjusted jest config to:
{
  "jest": {
    "transform": {
      // process `*.js` files with `babel-jest`
      ".*\\.(js)$": "babel-jest" //<-- changed this
    }
  }
}
  1. Adjusted babel config to:
module.exports = {
    presets: [
        '@vue/cli-plugin-babel/preset',
        '@babel/preset-env' //<-- added this
    ]
};

Answer №1

It is recommended to utilize the vue-cli API.

To enable this feature, simply add the following line to your package.json scripts:

"test:unit": "vue-cli-service test:unit"

With vue-cli and test-utils already installed, you should be all set to go.

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

What steps can I take to stop Vetur and TypeScript from displaying duplicate TypeScript warnings in VSCode?

I have a Vue2 project using TypeScript in VSCode with Vetur and TypeScript extensions installed. Whenever there is a TypeScript warning, both the TypeScript and Vetur overlays show duplicate warnings. Example of duplicate warnings Also, the intellisense ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

Modifying the hue of Material UI tab label

I attempted to modify the label color of a tab to black, but it seems to be stuck as white. Is this color hard-coded in material-ui? If not, how can I change it? Here's what I've tried: const customStyles = { tab: { padding: '2p ...

With Vue 3 Pinia, values fetched from an API within a Pinia store cannot be statically assigned; they will always be reactive

I have a frontend built with vue3 and using pinia as the store. I am setting it up as shown below: export const useShopStore = defineStore( "shop", () => { const state = reactive({ data: { fruits: [], owners: [] ...

A React component enclosed within a useCallback function

According to the React docs, to prevent a Child component from re-rendering in certain cases, you need to wrap it in useMemo and pass down functions in useCallback within the Parent component. However, I'm confused about the purpose of this implementa ...

Utilizing the arr.push() method to replace an existing value within an array with a new object, rather than simply adding a new

Seeking help to dynamically render a list of components that should expand or shrink based on values being added or removed from an array of custom objects. However, facing an issue where pushing a value into the array only replaces the previous value inst ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

How can I center the window vertically based on the middle of an element?

Hey guys, I need some help with my code. I've been trying to create a button that will shift the window's Y position to center the "Box - 5" div vertically through an onclick event. Basically, I want to make sure the "Box - 5" div is positioned i ...

Start Vue once the static data has been successfully loaded

I have a set of data that is not required to be constantly updated, and it originates from a remote source in the form of a JSON file generated by an admin on the server. This information may undergo periodic updates. In my Vue instance, I wish to incorpo ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

Differences between Angular's $injector and Angular's dependency injectionAngular

As a newcomer to Angular, I am exploring the use of $injector and its get function to retrieve specific services. For instance: app.factory('$myService', function($injector) { return { ... var http = $injector.get('$http&apos ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

Loss of image quality when utilizing Next/Image in NEXT JS

I am currently developing a web application using Next.js 13, and I recently noticed a decrease in the quality of my images. I'm not sure what went wrong or what I may have missed. Upon inspecting the HTML element on the browser, I found this code: & ...