Encountering issues with Jest Setup in Next.js as it appears to unexpectedly include a React import in index.test.js

Hey there, I've been pondering over this issue for the past few days. It appears to be a common error with multiple solutions.

I'm facing the dreaded:

Jest encountered an unexpected token
/__tests__/index.test.js:16
    import React from "react";
    ^^^^^^
SyntaxError: Cannot use import statement outside a module

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

I've gone through several posts and the documentation in Next.js and Jest. package.json:

    {
  "name": "some-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest --watch"
  },
  ...
}

index.test.js:

import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'
import React from "react";

describe('Home', () => {
  it('renders a h', () => {
    render(<Home />)

    const link = screen.getByRole('link', {
      name: "Library",
    })

    expect(link).toHaveAttribute('href', '/storage-area')
  })
});

jest.config.js:

...

In the title of my post, it seems like the error message indicates that the import is being added by Next.js at the end of index.test.js.

Answer №1

The issue arose from the placement of the tests folder, which was mistakenly nested in a directory above the project's root directory. Upon realizing this mistake, I noticed that I had made unnecessary changes to the jest.config.js file by adding imports to the transform: presets array, even though they were not needed in the standard jest/next configuration.

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

Displaying and Concealing Messages with VueJS

Currently, I have set up a basic CLI structure environment and created a component that displays messages/alerts such as "Login Failed." Since this component is intended to be reused throughout the entire app, I decided to import it into the root App.vue f ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

Exploring the OAuth 2.0 integration with OpenID Connect, Loopback, and Keycloak

I'm having trouble establishing a connection to Keycloak from Loopback. I've been experimenting with the keycloak-connect library available at: https://github.com/keycloak/keycloak-nodejs-connect This snippet shows my current implementation in ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...

Formik initialization does not prevent undefined errors in MUI textfield error and helpertext

It's perplexing why I keep encountering this issue - it has popped up a few times when attempting to utilize nested objects with Formik, React, and TypeScript. It appears that Formik is not compatible with data containing nested objects? https://i.st ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

What is the process for retrieving information from a retail outlet?

How can I retrieve data from the Vuex store using Vue.js? Below is my code: Vue.use(Vuex); export default new Vuex.Store({ modules: { data } }) data.js import axios from 'axios'; const state = { data: '' }; cons ...

Encountered a hiccup during the deployment of the React app to Heroku

Encountering an error while trying to deploy the react app on Heroku. Despite deleting package-lock.json and reinstalling npm, the same error persists. Any suggestions on resolving this issue would be highly appreciated. List of dependencies: "depend ...

Could someone assist me in figuring out the reason behind my fetch method sending undefined values?

Looking for some assistance with my fetch implementation issue. I am currently working on integrating stripe into my online grocery store website utilizing a node.js server with express, and ejs for frontend integration. The client-side JavaScript uses a f ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

The `npx create-react-app` command is asking for "Node 14 or higher," but my current Node version is 17.4.0. What steps can I take to resolve this issue?

Attempting to initiate a fresh React project on my Mac (running Mojave 10.14.5). After executing npx create-react-app my-app in VS Code's Terminal, I received an alert indicating that my Node version was outdated. Despite updating node to version 17. ...

Developing a mock login service in React using asynchronous functions and await keywords

In my project, I am working on creating a mock login button that should return a user object after 5 seconds of clicking the login button. Here is the event handler code for the login button: import UserService from "../services/user"; export default ...

Vue data will remain inaccessible until the JSON.stringify() function is executed

Dealing with this problem is tricky for me as it involves complex behavior that I haven't encountered before in JavaScript or Vue.js. I aim to simplify the code to focus on the most crucial aspects. I utilize vue-class-component (6.3.2) to define my ...

Utilizing Socket technology in combination with Sails JS and React JS

Currently, I have a live bidding system in place. On the bidding page, we display both the base price and current bid price of an item. Whenever a user updates the price of an item, I would like that new price to automatically reflect for all customers who ...

Tips for generating a document and adding information from an HTML webpage?

My desktop has an html file which requires input. How can I save this input to a file on my computer? Do I need to use a different language like python or javascript, and if so, how do I do it? Additionally, is there a way for javascript to launch an app ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

Ways to manage V-show in a dynamically changing environment

I am currently in the process of developing an Ecommerce shopping platform. I have been importing data from a JSON file and successfully printing it using a v-for loop. One feature I am implementing is the Show Order Details option, where clicking on it re ...

Can the color scheme be customized for both light and dark themes in Ant Design version 5?

After creating a hook that successfully toggles between light and dark modes in Chrome's Rendering panel, I noticed that the values in the ConfigProvider remain unchanged when switching themes. Can anyone suggest a workaround to modify the design toke ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...