Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "SyntaxError: Unexpected identifier" on Enzyme from configs in jest.setup.js

I'm trying to make my tests in Typescript with Jest and Enzyme but the tests throws a SyntaxError:

FAIL  src/_components/Button/__tests__/Button.spec.tsx
  ● Test suite failed to run

    /Users/mikaelboutin/Desktop/self/gatsby-react-intl-starter/jest.setup.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Enzyme, { mount, render, shallow } from 'enzyme'
                                                                                                    ^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

I tried to include ts-jest. It won't solve the problem. I changed many times the jest.config.js with some advices of many articles. I set a jest.preprocess.js` to pass babel presets to it.

I followed https://github.com/facebook/jest/issues/6229 but nothing do it on my project.

My repo is here: https://github.com/DWboutin/gatsby-intl-redux-typescript

jest.config.js

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.(ts|tsx)?$': `<rootDir>/jest-preprocess.js`
  },
  moduleNameMapper: {
    '.+\\.(css|styl|less|sass|scss)$': `identity-obj-proxy`,
    '.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `<rootDir>/__mocks__/file-mock.js`
  },
  testPathIgnorePatterns: [`node_modules`, `.cache`, `dist`],
  transformIgnorePatterns: [`node_modules/(?!(gatsby)/)`],
  globals: {
    __PATH_PREFIX__: ``
  },
  testURL: `http://localhost`,
  setupFiles: [`<rootDir>/jest.setup.js`, `<rootDir>/loadershim.js`],
  snapshotSerializers: ['enzyme-to-json/serializer']
}

jest.setup.js

import Enzyme, { mount, render, shallow } from 'enzyme'
import * as Adapter from 'enzyme-adapter-react-16'

// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() })
// Make Enzyme functions available in all test files without importing
global.shallow = shallow
global.render = render
global.mount = mount

jest.preprocess.js

const babelOptions = {
  presets: [
    [
      '@babel/preset-typescript',
      {
        isTSX: true,
        allExtensions: true
      }
    ],
    'babel-preset-gatsby'
  ]
}

module.exports = require('babel-jest').createTransformer(babelOptions)

loadershim.js

global.___loader = {
  enqueue: jest.fn(),
}

.babelrc

{
  "presets": [
    [
      "@babel/preset-typescript",
      {
        "isTSX": true,
        "allExtensions": true
      }
    ],
    "babel-preset-gatsby"
  ]
}

src/_components/Button/tests/Button.spec.tsx (my only test for now)

import { shallow } from 'enzyme'
import React from 'react'

import Button from '../'

describe('Button', () => {
  describe('Primary', () => {
    it('should match snapshot', () => {
      const wrapper = shallow(<Button>Test</Button>)

      expect(wrapper).toMatchSnapshot()
    })
  })
})

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "esnext",
    "jsx": "preserve",
    "lib": ["dom", "es2015", "es2017"],
    "strict": true,
    "noEmit": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": false,
    "preserveConstEnums": true
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules", "public", ".cache"]
}

package.json

{
  "name": "gatsby-starter-default",
  "description": "Gatsby default starter",
  "version": "1.0.0",
  "author": "Mikael Boutin <[email protected]>",
  "dependencies": {
    "@reach/router": "^1.2.1",
    "@types/styled-components": "^4.1.19",
    "classnames": "^2.2.6",
    "gatsby": "^2.15.18",
    "gatsby-image": "^2.2.19",
    "gatsby-plugin-manifest": "^2.2.17",
    "gatsby-plugin-offline": "^3.0.7",
    "gatsby-plugin-react-helmet": "^3.1.7",
    "gatsby-plugin-sharp": "^2.2.24",
    "gatsby-plugin-typescript": "^2.1.8",
    "gatsby-source-filesystem": "^2.1.24",
    "gatsby-transformer-sharp": "^2.2.15",
    "omit.js": "^1.0.2",
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-helmet": "^5.2.1",
    "react-intl": "^3.2.4",
    "react-redux": "^7.1.1",
    "redux": "^4.0.4",
    "styled-components": "^4.4.0",
    "typescript": "^3.6.3"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "start": "npm run develop",
    "format": "npm run format:src && npm run format:root",
    "format:src": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
    "format:root": "prettier --write \"./*.js\"",
    "transpile": "npm run build && babel src/_components/ --extensions \".ts,.tsx\" --ignore \"**/__tests__/**\" -d dist",
    "clean": "rm -rf .cache public dist",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "test:update": "jest --updateSnapshot"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.0",
    "@babel/preset-typescript": "^7.6.0",
    "@types/enzyme": "^3.10.3",
    "@types/enzyme-adapter-react-16": "^1.0.5",
    "@types/jest": "^24.0.18",
    "@types/mocha": "^5.2.7",
    "@types/node": "^12.7.5",
    "@types/react": "^16.9.2",
    "@types/react-dom": "^16.9.0",
    "@types/react-helmet": "^5.0.10",
    "babel-jest": "^24.9.0",
    "babel-preset-gatsby": "^0.2.14",
    "enzyme": "^3.10.0",
    "enzyme-adapter-react-16": "^1.14.0",
    "enzyme-to-json": "^3.4.0",
    "husky": "^3.0.5",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^24.9.0",
    "prettier": "^1.18.2",
    "react-test-renderer": "^16.9.0",
    "redux-devtools-extension": "^2.13.8",
    "source-map-support": "^0.5.13",
    "ts-jest": "^24.1.0",
    "ts-node": "^8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/DWboutin/gatsby-react-intl-starter"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run transpile"
    }
  }
}

I expected the tests to run correctly, but it throws a SyntaxError: Unexpected identifier on Enzyme.

Thank you for your help!

like image 499
Mike Boutin Avatar asked Sep 24 '19 15:09

Mike Boutin


1 Answers

From your jest.config.js you are not parsing .js files (jest.setup.js where the error comes from)

Modifying this line :

transform: {
    '^.+\\.(ts|tsx)?$': `<rootDir>/jest-preprocess.js`
  },

to add .js extensions like so:

transform: {
    '^.+\\.(ts|tsx|js)?$': `<rootDir>/jest-preprocess.js`
  },

Should do the trick.

Also, importing Adapter like this will throw an error

import * as Adapter from 'enzyme-adapter-react-16'

use this instead

import Adapter from 'enzyme-adapter-react-16'
like image 54
Dérick Paradis Avatar answered Oct 21 '22 17:10

Dérick Paradis