Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues.

When running the test suite, Jest successfully locates the file I intend to test but throws an Unexpected Identifier error message on line 1. Can anyone shed light on why this is happening? Am I missing something? I've been grappling with this for quite some time.

/Users/foo/Sites/test/Test.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Test from './Test.vue';
                                                                                                    ^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Please note that eliminating the import statements altogether allows the test to run successfully. Nevertheless, my primary reason for setting up Jest was to test Vue components.

Test.vue

<template>
        <div class="test">
        </div>
</template>

<script>
    export default {
        name: 'test',
        components: { },
        data() {
            return {

            }
        },
        methods: {
            helloWorld() {
                return 'hello world';
            }
        }
    }
</script>

Test.spec.js

import Test from './Test.vue'

describe('Test',() => {
   it('test', () => {
     expect(true).toBe(true);
   });
});

package.json

"devDependencies": {
    "@vue/test-utils": "^1.0.0-beta.25",
    "axios": "^0.18.0",
    "babel-core": "^6.26.0",
    "babel-jest": "^23.6.0",
    "babel-loader": "^7.1.2",
    "cross-env": "^5.1.1",
    "file-loader": "^2.0.0",
    "jest": "^23.6.0",
    "jquery": "^3.2",
    "laravel-mix": "^2.0",
    "lodash": "^4.17.4",
    "popper.js": "^1.14.3",
    "source-map-support": "^0.5.9",
    "vue": "^2.5.7",
    "vue-jest": "^3.0.0",
    "vue-test-utils": "^1.0.0-beta.11",
    "webpack": "^3.8.1"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "vue"
    ],
    "transform": {
      ".*\\.(vue)$": "vue-jest",
      "^.+\\.js$": "babel-jest"
    }
  }

Answer №1

When working with your test code that utilizes ES6 features, such as the import statement, it is necessary to transpile them into ES5 using a preset.

To achieve this, you can create a babel.config.js file and include @babel/preset-env in the presets array like shown below:

//babel.config.js
module.exports = {
  presets: ["@babel/preset-env"]
};

After setting up Babel, make sure to inform Jest about the root directory of your test code in package.json and specify the module directories that should be recursively searched by jest:

//package.json
"roots": [
  "test"
],
"moduleDirectories": [
  "test",
  "node_modules"
],

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

Does tns preview offer support for Vuex?

Since integrating Vuex into my NativeScript-Vue mobile app, I have encountered an issue where tns preview fails to resolve modules that rely on Vuex. Interestingly, the application functions properly when using tns run or tns build. This problem is prese ...

Vue: Order Conflict. A new module has been incorporated into the system

Whenever I try to run my program, something unexpected happens; How can I resolve this issue? I don't want to overlook it; I searched online and found suggestions to change the component order, but after checking my code, it didn't work; Any i ...

Modifying column layout within an HTML webpage

I'm seeking advice on modifying a code. I'd like to keep it the same as it is now, but with one change - I want to decrease the width of the main video box and add another one beside it with an iframe code for a chatbox. Here's the current c ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

Using JQuery to delete data from a cookie

I have a delicious cookie that I want to savor before removing one element from it based on the widget ID. if (thisWidgetSettings.removable) { $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) { ...

Optimal Approach for Managing Files in JavaScript

I have successfully uploaded a JSON file to my server using NodeJS and the 'http' module. Utilizing the NPM package 'formidable', I was able to save the file sent by the user onto the server. My next goal is to extract information from ...

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

Images are not appearing on Github pages

My website on GitHub Pages is not displaying images properly. Here is the link to my site: However, when I run it locally everything works fine. You can find the repository here: https://github.com/rsgrw23/rate-your-beer Can anyone pinpoint what might be ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Rendering React Router server-side with client-side session information

Currently, I am working with mozilla client-sessions in conjunction with express/node. My goal is to pass my session.user to the react-router within a standard * request. Despite my efforts and attempts, I keep encountering an issue where it becomes unde ...

Unable to find the locally stored directory in the device's file system using Nativescript file-system

While working on creating an audio file, everything seems to be running smoothly as the recording indicator shows no errors. However, once the app generates the directory, I am unable to locate it in the local storage. The code I am using is: var audioFo ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

What is the best way to securely transfer data from a Node/Express server to the client using JavaScript, ensuring sanitized HTML and preventing cross-site scripting (X

What is the best method to securely pass data from an Express backend to a client-side JavaScript in order to render it in the DOM using client-side rendering, while also allowing sanitized whitelist HTML and preventing XSS attacks? For example, if the No ...

Opening a fresh window with HTML content extracted from the existing page

Is there a way to open a new window and transfer some of the HTML content from the original page to the new window? For example: $("div#foo").click( function(){ var copyHTML = $("table.bar").html(); window.open(''); // how can we ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...