15.8 Jest에서 import/export를 사용하기

1. 설치

$ mkdir jest-using-import && cd jest-using-import
$ npm init -y
# jest를 설치하면 babel-jest가 자동 설치된다.
$ npm install -D jest @types/jest @babel/core @babel/preset-env

package.json

{
  "name": "jest-using-import",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.14.2",
    "@babel/preset-env": "^7.14.2",
    "@types/jest": "^26.0.23",
    "jest": "^26.6.3"
  }
}

2. 설정

.babelrc.json 생성

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

jest.config.json 생성

{
  "collectCoverage": true,
  "moduleFileExtensions": ["js", "mjs"],
  "transform": {
    "^.+\\.js$": "babel-jest",
    "^.+\\.mjs$": "babel-jest"
  },
  "testRegex": "((\\.|/*.)(test))\\.js?$"
}

3. 테스트

add.js 생성

function add(a, b) {
  return a + b;
}

export default add;

add.test.js 생성

import add from './add';

test('add(1, 2) is 3', () => {
  expect(add(1, 2)).toBe(3);
});

테스트 실행

$ npm test

> test@1.0.0 test
> jest

 PASS  ./add.test.js
  ✓ add(1, 2) is 3 (1 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 add.js   |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.11 s
Ran all test suites.
Back to top
Close