2

I'm trying to run a test in jest. When I add my import:

import { AnimalFactory } from "../../AnimalFactory";

I get the following error:

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from "axios/index";

SyntaxError: Cannot use import statement outside a module in Javascript/Jest

 

I believe something about import axios from axios/index is causing an issue. How can I fix this?

I read some suggestions to include "type": "module", so I've added to package.json as an additional line but nothing seems to change

I'm also getting this error:

Cannot find module 'axios/index' from 'AnimalFactory.js'

However, Jest was able to find:
    '../../AnimalFactory.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].

What i've done: installed babel and the plugin:

npm install --save-dev @babel/plugin-transform-modules-commonjs

webpack:

  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-proposal-class-properties",
      "@babel/plugin-transform-modules-commonjs"
    ]
  },
lost9123193
  • 10,460
  • 26
  • 73
  • 113
  • 1
    This is a deep rabbit hole that I dove into when trying to use Jest for client-side JS testing in Eleventy. Node.js by default is CommonJS which uses `module` and `require`. Maybe have a look at enabling [ES modules](https://jestjs.io/docs/en/ecmascript-modules) in your Jest config file. – Tanner Dolby Dec 09 '20 at 23:23
  • Jest doesn't work by default with ES6 imports so you should use something like babel to be able to use them. Check the answer to this question, probably it will be able to answer yours too - https://stackoverflow.com/questions/35756479/does-jest-support-es6-import-export – George Pandurov Dec 10 '20 at 00:16
  • @GeorgePandurov since axios is a library is it possible to added that in my ignored file paths from here in my package.json? testPathIgnorePatterns {....} – lost9123193 Dec 10 '20 at 00:42
  • Well, the problem is not axios itself, it's the import keyword so that wouldn't help you. Install babel and babel preset and copy from jest website the config for babel. I don't have my laptop with me now so I can't write the code to show it to you. – George Pandurov Dec 11 '20 at 09:40
  • I just saw that you have babel in your webpack, try adding babel.config.js from here https://jestjs.io/docs/en/getting-started#using-babel – George Pandurov Dec 11 '20 at 09:44

0 Answers0