[Setting | DevOps] jest 설정 및 sonarqube 연동

jest사용법을 정리하고 결과값을 sonarqube와 연동하여 시각화 하는 방법을 정리한다.


작성일 : 2022-06-05

1> jest 설치

npm install --save-dev jest

2> package.json 에 script 추가

{
  "scripts": {
    "test": "jest"
  }
}

3> sample code (sum.js)

function sum(a, b) {
    return a + b;
}
module.exports = sum;

4> test code (sum.test.js)

const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
});

5> test 실행

npm test
-----------------------------------------------------
> test
> jest

 PASS  nodejs/sum.test.js
  √ adds 1 + 2 to equal 3 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.513 s, estimated 1 s
Ran all test suites.
-----------------------------------------------------

6> sonarqube 연동설치

npm install --save-dev sonarqube-scanner
npm install --save-dev jest-sonar-reporter
// react app
npm install --save-dev jest-environment-jsdom
npm install --save-dev react-test-renderer

7> report 스크립트 작성 (report.js)

const sonarqubeScanner = require('sonarqube-scanner');
sonarqubeScanner(
    {
        options: {
            'sonar.projectName': 'sample',
            'sonar.projectKey': 'sample',
            'sonar.host.url': 'http://localhost:7777',
            'sonar.login': '177a4fe55dc2cb35879742e2baa13c7f566564db',
            'sonar.sources': 'src',
            'sonar.tests': 'src',
            'sonar.inclusions': '**',
            'sonar.test.inclusions': 'src/**/*.spec.js,src/**/*.spec.jsx,src/**/*.test.js,src/**/*.test.jsx',
            'sonar.javascript.lcov.reportPaths': 'coverage/lcov.info',
            'sonar.testExecutionReportPaths': 'coverage/cover.xml',
        },
    },
    () => process.exit(),
);
module.exports = sonarqubeScanner;

8> package.json 에 script 추가 및 설정

{
  "scripts": {
    "test": "jest",
    "test:coverage": "jest --coverage",
    "sonar": "node report.js"
  },
...
  "jest": {
    "testResultsProcessor": "jest-sonar-reporter"
  },
...
  "jestSonar": {
    "reportPath": "coverage",
    "reportFile": "cover.xml"
  }
}

9> 테스트 실행

npm run test:coverage
npm run sonar