Testing ES6 module in mocha

테스트 프레임워크 mocha에서 ES6 모듈 import 후 테스트를 하려면 몇가지 설정을 추가해야 합니다.

1. Installing dependencies

install mocha as devDependencies

console
$ npm install mocha --savedev

install @babel/XXX as devDependency

console
$ npm install \ @babel/cli \ @babel/core \ @babel/preset-env \ @babel/register \ --save-dev

package.json should be like

package.json
{ "scripts": { ... } "devDependencies": { "@babel/cli": "^7.15.7", "@babel/core": "^7.15.5", "@babel/preset-env": "^7.15.6", "@babel/register": "^7.15.3", ... "mocha": "^9.1.2", ... }, ... }
  • mocha 9.x.x
  • babel 7.x.x

2. Creating babel configuration file

Create a file .babelrc in [ROOT-DIR]

TXT
[ROOT-DIR] +- src +- test +- package.json +- .babelrc (+)

input the content

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

3. Sample files

We will create two files to validate current configuration

  • src/calc.js - source file under test
  • test/calc.spec.js - test file
TXT
[ROOT-DIR] +- src +- calc.js (+) +- test +- calc.spec.js (+) +- package.json +- .babelrc

input the content

src/calc.js
const add = (a, b) => a + b const mul = (a, b) => a - b export default { add, mul }
test/calc.spec.js
import assert from 'assert' import calc from '../src/calc' describe('testing calculator', () => { it('should be seven', () => { const seven = calc.add(3, 4) assert.equal(7, seven) }) })

4. Test Command

Now, create test command in package.json to be executed with npm run ...

package.json
{ "scripts" { "build": ... , "start": ... , "test": mocha --require @babel/register (+) } }

5. Test run

run in terminal

console
$ npm run test
  • npm run test - will execute 'test' of "scripts" in package.json

result

test_result
$ npm run test testing calculator ✔ should be seven 1 passing (7ms)