4

I'm trying to make a complex zip extractor in JavaScript and I decided that unit testing would be very important. That being said, a friend recommended Jest. I couldn't get any of my tests to work so I made a dumb test that made sure the first value of my JS Enum is 0. Jest, however, fails ever time saying that it encountered an unexpected token

I tried a more complex test and simplified it down to this simple test:

enums.js:

const Format = {
    UNKNOWN: 0,
    ZIP: 1,
    TAR_GZIP: 2,
    TAR_BZIP: 3,
};

export default Format

enums.test.js

const {Format} = require("../src/enums.js");

test("bad test", () => {
   expect(Format.UNKNOWN).toBe(0);
});

The error that is gives me is this:

Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/giovanni/WebstormProjects/extract.js/src/enums.js:7
    export default Format;
    ^^^^^^

    SyntaxError: Unexpected token export

    > 1 | const Format = require("../src/enums.js");
        | ^
      2 | 
      3 | test("bad test", () => {
      4 |    expect(Format.UNKNOWN).toBe(0);

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (test/enum.test.js:1:1)

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • You don't need `{}` around as `Format` is default exported – Code Maniac Aug 06 '19 at 02:23
  • 1
    can you try using [`module.exports`](https://www.tutorialsteacher.com/nodejs/nodejs-module-exports) instead of `export`? I think jest does not support es6 by default. You need to use babel. see [this](https://stackoverflow.com/questions/35756479/does-jest-support-es6-import-export) answer for babel solution – kkesley Aug 06 '19 at 05:34
  • You probably need to allow jest transpiling modules before testing. – entio Aug 06 '19 at 08:29

1 Answers1

0

Using Bable fixed this. Once I installed Babel with NPM, I added a file .babelrc with the contents:

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

This worked.