Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected token, expected ";" on import JSON in NodeJS jest testing

I have a NodeJS project using Jest and babel. When I run the test I get the following error:

FAIL ./user.test.js ● Test suite failed to run. SyntaxError: C:\Users\...\__test__\mocks\registerUser.json: Unexpected token, expected ";" (2:8) When i change the registerUser.json to a javascript file I'm able to retrieve the content without any problem, but when I try to use a JSON file won't work. But I can't seem to find the cause of the error when using a json file.

My current structure is something like:

|-- src
|-- __test__
     |-- mocks
        |-- registerUser.json
     |-- user.test.js
|-- tmp
.babelrc
.eslintignore
.eslintrc
.gitignore
.prettierrc
jest.config.js
package.json

user.test.js

const userRegisterMock = require('./mocks/registerUser.json');

describe('User', () => {
  it('[SUCCESS] should be able to register', async () => {
    // console.log(userRegisterMock)
    expect(true).toBe(true);
  });
});

jest.config.js

    module.exports = {
      bail: 1,
      testEnvironment: 'node',
      clearMocks: true,
      collectCoverage: true,
      collectCoverageFrom: [
        'src/**',
        '!src/helpers/**',
        '!src/app.js',
        '!src/server.js',
        '!src/database/**',
        '!src/config/**'
      ],
      coverageDirectory: '__tests__/coverage',
      coverageReporters: ['text', 'lcov'],
      coverageThreshold: {
        global: {
          branches: 100,
          functions: 100,
          lines: 100,
          statements: 100
        }
      },
      moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
      resetModules: false,
      testMatch: ['**/__tests__/**/*.test.js'],
      transform: {
        '.(js|jsx|ts|tsx)': 'babel-jest'
      }
    };

.babelrc

{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage", // or "entry"
      "corejs": 3,
      "targets": {
        "node": "current"
      }
    }]
  ],
  "plugins": [
    ["@babel/plugin-transform-modules-commonjs"],
    ["@babel/plugin-transform-runtime", {
      "regenerator": true
    }]
  ]
}

registerUser.json

{
  "name": "Test Case",
  "country": "Brazil",
  "birthdate": "25/03/1994",
  "sex": "Masculino",
  "nationality": "Brasileiro"
}
like image 227
bsantoss Avatar asked Sep 16 '26 03:09

bsantoss


1 Answers

Your transform regex contains .js which matches `.json

If you add an $ in the end, you'll select only files ending with .js.

transform: {
  '.(js|jsx|ts|tsx)$': 'babel-jest'
}

An even better regex would be: '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest'

like image 132
Andre Goulart Avatar answered Sep 18 '26 17:09

Andre Goulart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!