javascriptecmascript-6jestjsbabeljstestunit

Javascript Test unit with Jest an ES6 module


too many divergent posts upon googling to choose a clear and up-to-date solution...

I wrote 3 tests to check different possibilities

===========. TEST 1 OK ================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
module.exports = sayHello;

// helloJestTest

const sayHello = require('../../src/client/js/helloJest');
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

===========. TEST 2 FAILING ================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
export default { sayHello }; // <= changed

// helloJestTest

const sayHello = require('../../src/client/js/helloJest');
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

TypeError: sayHello is not a function

      3 |
      4 | test('string returning hello there jest', () => {//
    > 5 |   expect(sayHello()).toEqual('hello there jest');
        |          ^
      6 | });
      7 |

===========. TEST 3 FAILING ================

// helloJest.js

function sayHello() {
  return "hello there jest"
}
export default { sayHello }; //  <= changed

// helloJestTest

import { sayHello } from '../../src/client/js/helloJest'; // <= changed
test('string returning hello there jest', () => {// 
  expect(sayHello()).toEqual('hello there jest');
});

    TypeError: (0 , _helloJest.sayHello) is not a function

      3 |
      4 | test('string returning hello there jest', () => {//
    > 5 |   expect(sayHello()).toEqual('hello there jest');
        |          ^
      6 | });

How to pass the TEST 3 correctly ???

I am using the following packages

package.json

"babel-core": "^6.26.3",
"babel-jest": "^23.6.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
...
"jest": {
    "moduleFileExtensions": ["js"],
    "transform": { "^.+\\.js?$": "babel-jest" },
    "testRegex": "/tests/.*\\.(js)$"
  }

and I have in

.babelrc

{
  "presets": ["env"]
}

Solution

  • You're tripping up in a couple of places there. Primarily: You don't use {} with the default import/export.

    This:

    export default { sayHello };
    

    exports an object as the default export of the module. The object has a single property, sayHello, referring to the function. To make the function the default export, don't use the {}:

    export default sayHello;
    

    Then, when importing, if you want the default import, don't use {}:

    import sayHello from '../../src/client/js/helloJest';
    

    If you want to export a named export, you do use {}:

    export { sayHello };
    

    and

    import { sayHello } from '../../src/client/js/helloJest';
    

    Examples of both on plunker: https://embed.plnkr.co/f8PhOhULphQUrVXwdXF3/