NUXT에서 JEST를 이용한 테스트

2019. 10. 21. 02:00서버 프로그래밍

쓸만한 레퍼런스가 있어서 어렵지 않게 처리했으나, 역시나 예외 상황은 발생한다.

https://medium.com/@changjoopark/nuxt-js%EC%97%90-jest-storybook-%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0-7f819ef6d4f8

 

Nuxt.js에 Jest설치하기

Vue.js 프로젝트는 보통 vue-cli 를 이용해 스캐폴딩합니다. Nuxt는 nuxt-community 조직을 통해 starter-template, typescript-template 또는 express-template을 제공하는데 대부분의…

medium.com

의존성 설치

npm의 경우

npm install --save-dev babel-jest jest jest-vue-preprocessor @vue/test-utils

package.json에 아래 내용을 추가합니다.// ...
"jest": {
"verbose": true,
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor"
},
"moduleNameMapper": {
"^vue$": "vue/dist/vue.common.js",
"^~/(.*)$": "<rootDir>/$1"
},
"collectCoverage": true,
"collectCoverageFrom": [
"**/components/**/*.{js, vue}",
"**/server/utils/*.{js}",
"!**/node_modules/**"
],
"coverageReporters": [
"text-summary"
]
}

위 JSON 설정을 추가하고 script를 추가해 npm run test 명령어가 실행되면 자동으로 테스트 파일을 감시하도록 합니다.

"test": "jest --watchAll"

모듈 테스트

Vue 컴포넌트 테스트 전에 간단한 sum 메소드를 이용해 Jest가 잘 추가되었는지 확인합니다.

우선 <my-project>/tests/sum.test.js 파일을 만듭니다. test 스크립트가 실행중이면 자동으로 감지하여 테스트를 시작합니다.

describe('sum 메소드 테스트', () => {
test('1 + 1 === 2 (Jest 테스트를 위함)', () => {
expect(1+1).toBe(2)
})
})

위 테스트를 추가하고 저장하면 테스트 결과를 볼 수 있습니다.

파일을 이용해 만든 테스트가 아니므로 utils 디렉터리를 만들고 테스트를 수정합니다. 이 글은 Jest 테스트를 자세히 다루는 글이 아니므로 바로 sum 메소드를 구현하고 테스트까지 완료합니다.

// <my-project>/utils/sum.js
const sum = (a, b) => {
return a + b
}
module.exports = sum// <my-project>/tests/sum.tests.js
const sum = require('../utils/sum')
describe('sum 메소드 테스트', () => {
test('1 + 1 === 2 (Jest 테스트를 위함)', () => {
expect(sum(1,2)).toBe(3)
})
})

Jest 설치가 정상적으로 되어있는지 확인이 완료되었으므로 vue-test-utils를 확인할 차례입니다.

Vue 컴포넌트 테스트

위 테스트에서 import , export 등의 키워드를 사용하지 않았는데, Vue 컴포넌트 테스트를 위해선 .babelrc 파일을 프로젝트 루트에 추가해야합니다.

{
"presets": [
"env"
]
}

*** 이대로 실행시 다음과 같은 에러가 발생한다.

 FAIL  tests/sum.test.js
  ● Test suite failed to run

    Cannot find module 'babel-preset-env' from 'C:\Users\jeong\web-xsync-admin-2.0-publishing'
    - Did you mean "@babel/env"?

      at Function.module.exports [as sync] (node_modules/resolve/lib/sync.js:74:15)
      at resolveStandardizedName (node_modules/@babel/core/lib/config/files/plugins.js:101:31)
      at resolvePreset (node_modules/@babel/core/lib/config/files/plugins.js:58:10)
      at loadPreset (node_modules/@babel/core/lib/config/files/plugins.js:77:20)
      at createDescriptor (node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
      at items.map (node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
          at Array.map ()
      at createDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
      at createPresetDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
      at presets (node_modules/@babel/core/lib/config/config-descriptors.js:47:19)

*** package.json에 다음 항목 추가한다. 아래는 참고 레퍼런스 링크이다.

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

https://github.com/babel/babel-loader/issues/616

 

Cannot find module 'babel-preset-env' · Issue #616 · babel/babel-loader

I'm submitting a bug report Webpack Version: 3.12 Babel Core Version: 7.0.0-beta.46 (also "@babel/preset-env": "^7.0.0-beta.46") Babel Loader Version: 8.0.0-beta.2 Please te...

github.com

이제 Jest 테스트에서 import와 export를 사용할 수 있게 되었습니다. sum 메소드에는 직접 적용해보세요

Nuxt.js 프로젝트를 스캐폴딩하면 기본으로 제공하는 Logo.vue 컴포넌트를 테스트하겠습니다.

테스트할 내용은 Logo 컴포넌트가 Vue.js 컴포넌트인지, 그리고 4개의 Triangle 클래스를 가지는 <div> 엘리먼트가 있는가 입니다.

Logo 컴포넌트가 Vue 컴포넌트인지 테스트

주의해야할 점은 싱글파일 컴포넌트(.vue 파일)에 반드시 <script></script> 태그가 있어야합니다. script 태그가 없으면 Jest가 파일을 가져와도 테스트를 할 수 없습니다.

import { mount } from '@vue/test-utils'
import Logo from '../components/Logo.vue'
describe('로고 컴포넌트', () => {
let wrapper
beforeEach(() => {
wrapper = mount(Logo)
})
test('로고 컴포넌트는 Vue 인스턴스이다.', () => {
expect(wrapper.isVueInstance()).toBeTruthy()
})
})

첫번째 테스트입니다. beforeEach 메소드에서 각 테스트마다 wrapper 변수에 Logo 컴포넌트를 마운트합니다.

*** 테스트 실행시 typescript 없다는 에러가 뜬다

 FAIL  tests/Logo.test.js
  ● Test suite failed to run

    Cannot find module 'typescript'

      at Object. (node_modules/jest-vue-preprocessor/transforms/transformTs.js:4:13)

*** typescript 모듈을 추가하여 해결하면 된다.

npm install --save-dev typescript

4개의 Triangle 클래스를 가지는지 테스트

// ...
test('4개의 Triangle 클래스를 가진다.', () => {
expect(wrapper.findAll('.Triangle').length).toBe(4)
})
// ...

이번에도 테스트가 성공 합니다. 실패하는 테스트를 보려면 toBe 안의 4를 다른 숫자로 바꾸어보세요.

https://jestjs.io/docs/en/getting-started

 

Jest · 🃏 Delightful JavaScript Testing

🃏 Delightful JavaScript Testing

jestjs.io

* 기타 자료

https://joshua1988.github.io/vue-camp/testing/jest-testing.html#jest-api

 

Unit Testing with Jest | Cracking Vue.js

Jest 소개 제스트(Jest)는 페이스북에서 만든 자바스크립트 테스팅 라이브러리입니다. 테스트 코드의 모양이 직관적이고 문서화가 잘되어 있어 요즘 많이 활용되고 있습니다. 라이브러리 설치 제스트는 NPM으로 아래와 같이 설치합니다. 테스트 파일 생성 파일 위치 : 테스트 할 파일이 있는 폴더 내 폴더 이름 : __test__ 파일 이름 : 파일 이름.test.js 또는 파일 이름.spec.js 테스트 코드 실행 제스트를 설치하고 나면 콘솔 창에 아래와

joshua1988.github.io

https://codeburst.io/nuxt-unit-snapshot-testing-a3dc7cb79ec1

 

Nuxt unit + snapshot testing

Nuxt is great but unit testing is a pain point.

codeburst.io

https://github.com/wesssel/nuxt-unit-testing

 

wesssel/nuxt-unit-testing

Nuxt template including unit testing. Contribute to wesssel/nuxt-unit-testing development by creating an account on GitHub.

github.com

https://learntdd.in/vue/

 

Learn TDD in Vue

Learn test-driven development in your framework of choice.

learntdd.in

https://www.valentinog.com/blog/jest/

 

Jest Tutorial for Beginners: Getting Started With JavaScript Testing

What means testing? How to test JavaScript code with Jest? Learn the basics of testing JavaScript with this Jest tutorial for beginners!

www.valentinog.com

https://medium.com/@gogl.alex/nuxt-jest-setup-from-scratch-8905d3880daa

 

Nuxt + Jest setup from scratch

Setting up testing can be very daunting: especially if you are just starting out. When I started out with Vue and Nuxt, I didn’t really…

medium.com

https://vue-test-utils.vuejs.org/guides/#getting-started

 

Guides | Vue Test Utils

Guides Getting Started Setup To get a quick taste of using Vue Test Utils, clone our demo repository with basic setup and install the dependencies: If you already have a project that was craeted with the Vue CLI and want to add testing capabilities you may

vue-test-utils.vuejs.org

https://alligator.io/vuejs/testing-vue-with-jest/

 

Testing Vue with Jest

In this post we're going over getting setup to test Vue applications using vue-test-utils and Jest.

alligator.io