Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected token import es6 class #6404

Closed
bredah opened this issue Jun 6, 2018 · 3 comments
Closed

Unexpected token import es6 class #6404

bredah opened this issue Jun 6, 2018 · 3 comments

Comments

@bredah
Copy link

bredah commented Jun 6, 2018

🐛 Bug Report

When I run JEST, the execution failed and show the message:

> [email protected] test C:\Users\bredah\git\lab_js\es6                                                                    
> jest                                                                                                                                      
                                                                                                                                            
 FAIL  src/example/calculator.spec.js                                                                                                       
  ● 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://facebook.github.io/jest/docs/en/configuration.html                                                                              
                                                                                                                                            
    Details:                                                                                                                                
                                                                                                                                            
    C:\Users\bredah\git\lab_js\es6\src\example\calculator.spec.js:1                                                                 
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Calculator } from './calculator';     
                                                                                             ^^^^^^                                         
                                                                                                                                            
    SyntaxError: Unexpected token import                                                                                                    
                                                                                                                                            
      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:402:17)                          
                                                                                                                                            
Test Suites: 1 failed, 1 total                                                                                                              
Tests:       0 total                                                                                                                        
Snapshots:   0 total                                                                                                                        
Time:        5.468s                                                                                                                         
Ran all test suites.                                                                                                                        
npm ERR! code ELIFECYCLE                                                                                                                    
npm ERR! errno 1                                                                                                                            
npm ERR! [email protected] test: `jest`                                                                                            
npm ERR! Exit status 1                                                                                                                      
npm ERR!                                                                                                                                    
npm ERR! Failed at the [email protected] test script.                                                                              
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.                                          
                                                                                                                                            
npm ERR! A complete log of this run can be found in:                                                                                        
npm ERR!     C:\Users\bredah\AppData\Roaming\npm-cache\_logs\2018-06-06T12_27_15_540Z-debug.log                                     

To Reproduce

Execute the command:

λ npm run test

Expected behavior

Executing all test without any error.

Code

.
│   .jshintrc
│   package-lock.json
│   package.json
├───src
│   └───example
│           calculator.js
│           calculator.spec.js

File packages.json

{
  "name": "example_js_unit_test",
  "version": "1.0.0",
  "description": "Example: How to use develop unit test with JS",
  "main": "",
  "scripts": {
    "test": "jest"
  },
  "author": "bredah",
  "license": "ISC",
  "devDependencies": {
    "jest": "^23.1.0"
  }
}

File: calculator.js

class Calculator {

    constructor(){
    }

    result(varA, varB, equation) {
        if (equation == null) {
            throw new Error('Not exist equation with NUL value');
        }
        var value = 0;
        switch (equation.toLowerCase()) {
            case 'add':
                value = varA + varB;
                break;
            case 'subtract':
                value = varA - varB;
                break;
            case 'multiply':
                value = varA * varB;
                break;
            case 'divide':
                value = varA / varB;
                break;
            default:
                value = 0;
                break;
        }
        return value;
    }
}

export { Calculator };

File: calculator.spec.js

import { Calculator } from './calculator';

let calc = null;

beforeEach(() => {
  calc = new Calculator();
});

afterEach(() => {
});

test('Add', () => {
  var result = calc.result(4, 2, 'add');
  expect(result).toBe(6);
});

test('Subtract', () => {
  var result = calc.result(4, 2, 'subtract');
  expect(result).toBe(2);
});

test('Multiply', () => {
  var result = calc.result(4, 2, 'multiply');
  expect(result).toBe(8);
});

test('Divide', () => {
  var result = calc.result(4, 2, 'divide');
  expect(result).toBe(2);
});

test('Equation not exist', () => {
  var result = calc.result(4, 2, 'x');
  expect(result).toBe(0);
});

test('Equation void', () => {
  var result = calc.result(4, 2, '');
  expect(result).toBe(0);
});

test('Equation null', () => {
  expect(calc.result(4, 2, null)).toThrow(Error);
});

Run npx envinfo --preset jest

λ npx envinfo --preset jest
npx: installed 1 in 6.787s
Path must be a string. Received undefined
npx: installed 1 in 4.451s
C:\Users\bredah\AppData\Roaming\npm-cache\_npx\148484\node_modules\envinfo\dist\cli.js

  System:
    OS: Windows 10
    CPU: x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
  Binaries:
    Yarn: 1.6.0 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 6.1.0 - C:\Program Files\nodejs\npm.CMD
@thymikee
Copy link
Collaborator

thymikee commented Jun 6, 2018

This is not a bug. You need to configure Babel properly to use ES6 modules with Jest. Please read our documentation, or have a better search on this issue tracker or Stack Overflow.

@thymikee thymikee closed this as completed Jun 6, 2018
@Nantris
Copy link

Nantris commented Jun 24, 2018

Seems like there's a possible bug here.

Example 1 - Trying to import a non-existent path

import { expectSaga } from 'redux-saga-test-plan';
import database from '../wrongPath/database';

This fails because it can't find database, NOT because Unexpected token import

Example 2 - Trying to import a from the correct path

import { expectSaga } from 'redux-saga-test-plan';
import database from '../rightPath/database';

Fails on the first import with Unexpected token import


I would expect an improper babel configuration would result in Unexpected token import in both examples, but I'm only seeing it when I ask for an existent path.

The import that is failing is the first line of example 2, not an import within another file.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants