Using ES6 import and export statements for Jest testing in Node.js

Sola-Aremu 'Pelumi
2 min readDec 12, 2019

Currently, Node.js does not support using the import and export statements as released in the ES6 version of Javascript. The import and export statements are a part of the ECMAScript modules which allow for a more natural method to access functions across multiple files.

Although this functionality is contained in the Node.js 13 version, this article should still come in handy for users of previous versions of Node.js especially with respect to testing in Jest.

For developers used to working with the ES6 release of JavaScript, reverting to module.exports syntax might be a bit of a drawback. We’d quickly configure a Node.js project to use the import and export statements in running tests in Jest.

We would need to add Babel which helps transpile JavaScript into formats old browsers are capable of recognizing. In this case, its the ES6 import and export statements it helps us with.

mkdir test_calc && cd test_calc
npm init

While setting up your project configuration, remember to include jest as your testing framework.

Now, using the node package manager, we proceed to add Babel, jest, and babel-jest

npm install --save-dev jest babel-jest @babel/preset-env 

We then need to configure Babel to use the current version of Node.js and help transpile our code. We can do this by creating a babel config file at the root of our project and adding the following configuration

vi babel.config.js

We can then begin to write the actual code. Following TDD, let’s write our test file first

vi test_calc.test.js

Then the actual logic

vi test_calc.js

We can then go ahead to check that everything works fine

npm test

--

--

Sola-Aremu 'Pelumi

I sometimes get interesting thoughts and the urge to share. You would find me playing at the intersection of technology and society.