简体   繁体   中英

"SyntaxError: Cannot use import statement outside a module" error while testing a Nodejs project with Jest

So I'm working on a Nodejs project with expressjs and I'm trying to use Jest to test my apis. I've read about configuring Jest in the documentation, but I'm new to jest and it's a bit confusing. The error I'm getting :

SyntaxError: Cannot use import statement outside a module at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)

My test file:

const userController = require("../controllers/user.controller");
const router = require("../routes/user.routes");


//Testing login route
describe("POST /api/user/login", () => {
    describe("given a username and password", () => {
  
      test("should respond with a 200 status code", async () => {
        const response = await request(router).post("/login").send({
          username: "username",
          password: "password"
        })
        expect(response.statusCode).toBe(200)
      })
     })
  

  
  })

I had to install babel-jest

"devDependencies": {
    "@babel/core": "^7.18.6",
    "@babel/preset-env": "^7.18.6",
    "babel-jest": "^28.1.2",
    "jest": "^28.1.2",
    "supertest": "^6.2.4"
  }

and added a file called .babelrc to my project containing this code:

{
    "presets": [
      "@babel/preset-env"
    ]
  }
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM