Nuxt로 Vuex를 테스트하는 방법

27040 단어 webdevtddvuenuxt
안녕하세요, 이 기사에서는 Vuex를 테스트하는 방법을 배웁니다. Nuxt.js 프레임워크를 사용하여 프로젝트를 생성할 것입니다. 먼저 Vuex는 Vuex가 Vue.js 애플리케이션의 상태 관리 표준입니다. 상태가 예측 가능한 방식으로만 변경될 수 있도록 하는 규칙을 사용하여 응용 프로그램의 모든 구성 요소에 대한 중앙 집중식 저장소 역할을 합니다. 우리 프로젝트는 간단한 프로젝트가 될 것입니다. 숫자를 늘리고 줄이는 응용 프로그램이 될 것입니다. 시작하겠습니다.

Vue 설치:

npm install -g @vue/cli
# OR
yarn global add @vue/cli


다음 명령으로 올바른 버전인지 확인할 수 있습니다.

vue --version


프로젝트를 만들 때 구성을 자유롭게 선택할 수 있는 몇 가지 프로젝트 구성 옵션이 있지만 테스트 프레임워크에서 Jest를 선택해야 합니다. 이 프로젝트를 만들 때 선택한 옵션을 보여 드리겠습니다.

Programing language: Javascript
Package manager: npm 
UI framework: none
Nuxt.js modules: axios
Linting tools: Eslint, Prettier e Lint staged files
Testing framework: Jest
Rendering mode: Universal
Deployment target: Serve
Deployment tools: jsconfig
Continuous integration: None
Version control system: Git


프로젝트 생성 명령:

npm init nuxt-app <project-name>
# OR
npx create-nuxt-app <project-name>


좋아요, 프로젝트를 생성한 후 테스트 개발에 도움이 될 종속성을 설치하겠습니다.

npm install @types/jest --save-dev


모든 설치가 끝나면 package.json 파일로 이동하여 스크립트를 하나 더 추가합니다.

"test:watch": "jest --watchAll",
"test:coverage": "jest --coverage",


스크립트를 실행하기 전에 jest.config.js 파일로 이동하여 몇 가지를 변경하고, collectCoverage에 false 값을 추가하세요. 이렇게 하면 프로젝트에 대한 각 변경 사항에 대한 적용 범위가 생성되지 않으며 다음 변경 사항은 store에서 collectCoverage에 추가됩니다./store/*/.js 디렉토리는 jest가 저장소 폴더에서 실행되도록 합니다.

이제 다음 명령을 실행할 수 있습니다.

npm run test:watch


이제 프로젝트가 테스트를 실행 중입니다. 이 설정을 마치면 실습을 시작하겠습니다. nuxt.js의 다음 이름 카운터를 사용하여 저장소 폴더에 파일을 생성하고 이미 파일에 입력한 이름으로 파일 내보내기를 수행합니다. nuxt .js는 이미 이 작업을 자동으로 수행합니다. 우리 기사에서 우리는 응용 프로그램의 모든 상태를 포함하고 "진실의 단일 소스"역할을 하는 객체인 상태와 Vuex 스토어에서 실제로 상태를 변경하는 유일한 방법인 변형이 필요합니다.

테스트를 먼저 작성하는 TDD 방식(Test Driven Development)을 사용하여 개발 중이므로 기능이 이제 테스트 파일이 될 또 다른 파일을 생성할 예정이므로 파일 이름은 counter.unit.spec.js가 될 수 있습니다. 카운터가 있는 동일한 폴더 또는 테스트 폴더에 생성되어야 합니다.

테스트를 수행하기 위해 필요한 가져오기를 수행할 것입니다. createLocalVue, vuex 및 해당 저장소를 가져와야 합니다. 다음과 같이 유지됩니다.

import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { mutations, state } from '@/store/counter.js'


이제 먼저 테스트를 생성하겠습니다. describe 안에 테스트를 그룹화하고 해당 테스트가 무엇인지 설명합니다. describe 내부에서 우리는 스토어를 호출하고 반환할 함수를 생성할 것이며 이 스토어를 사용하여 상태, 돌연변이, 작업 및 게터에 액세스할 수 있습니다. 함수를 사용한 설명은 다음과 같습니다.

describe('Counter store', () => {
  const createStore = () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const store = new Vuex.Store({ state, mutations })

    return { store }
  }
})


우리가 만들 첫 번째 테스트는 초기 값이 0인 카운터 값의 상태를 확인하는 테스트입니다. 첫 번째 테스트는 다음과 같습니다.

describe('Counter store', () => {
  const createStore = () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const store = new Vuex.Store({ state, mutations })

    return { store }
  }

  it('State => counter should start with the value zero', () => {
    const { store } = createStore()
    expect(store.state.counter).toEqual(0)
  })
})


이제 증가 방법이 호출될 때 변이를 테스트해 보겠습니다. 카운터 값이 한 번 더 증가해야 합니다. 예를 들어 증가가 호출될 때 카운터 값은 0이고 카운터 값은 1이어야 합니다. 코드는 다음과 같습니다.

describe('Counter store', () => {
  const createStore = () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const store = new Vuex.Store({ state, mutations })

    return { store }
  }

  it('State => counter should start with the value zero', () => {
    const { store } = createStore()
    expect(store.state.counter).toEqual(0)
  });
  it('Mutation => should increment one more when increment is called ', () => {
    const { store } = createStore()
    store.commit('increment')
    expect(store.state.counter).toEqual(1)
    store.commit('increment')
    expect(store.state.counter).toEqual(2)
  })

})


이제 카운터 값이 1만큼 더 감소해야 하는 호출이 있을 때 감소 방법을 테스트해 보겠습니다. 예를 들어 증분이 호출될 때 카운터 값은 0이고 카운터 값은 -1이어야 합니다. 코드는 다음과 같습니다.

describe('Counter store', () => {
  const createStore = () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const store = new Vuex.Store({ state, mutations })

    return { store }
  }

  it('State => counter should start with the value zero', () => {
    const { store } = createStore()
    expect(store.state.counter).toEqual(0)
  });
  it('Mutation => should increment one more when increment is called ', () => {
    const { store } = createStore()
    store.commit('increment')
    expect(store.state.counter).toEqual(1)
    store.commit('increment')
    expect(store.state.counter).toEqual(2)
  });
it('Mutation => should decrement one more when decrement is called ', async () => {
    const { store } = createStore()
    await store.commit('decrement')
    expect(store.state.counter).toEqual(-1)
    await store.commit('decrement')
    expect(store.state.counter).toEqual(-2)
  })

})


마지막 테스트는 카운터 값을 재설정하는 것입니다. 이 메서드의 이름은 재설정되며 호출되면 카운터 값을 재설정해야 합니다. 테스트는 다음과 같습니다.

describe('Counter store', () => {
  const createStore = () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const store = new Vuex.Store({ state, mutations })

    return { store }
  }

  it('State => counter should start with the value zero', () => {
    const { store } = createStore()
    expect(store.state.counter).toEqual(0)
  });
  it('Mutation => should increment one more when increment is called ', () => {
    const { store } = createStore()
    store.commit('increment')
    expect(store.state.counter).toEqual(1)
    store.commit('increment')
    expect(store.state.counter).toEqual(2)
  });
it('Mutation => should decrement one more when decrement is called ', () => {
    const { store } = createStore()
    store.commit('decrement')
    expect(store.state.counter).toEqual(-1)
    store.commit('decrement')
    expect(store.state.counter).toEqual(-2)
  });
it('Mutation => should reset counter when reset is called ', () => {
    const { store } = createStore()
    store.commit('increment')
    store.commit('reset')
    expect(store.state.counter).toEqual(0)
    store.commit('decrement')
    store.commit('reset')
    expect(store.state.counter).toEqual(0)
  })

})


저장소 폴더의 카운터 파일 코드는 다음과 같습니다.

export const state = () => ({
  counter: 0,
})

export const mutations = {
  increment: (state) => {
    state.counter++
  },
  decrement: (state) => {
    state.counter--
  },
  reset: (state) => {
    state.counter = 0
  },
}

export const actions = {}

export const getters = {}



기사를 읽어주셔서 감사하고 vuex 테스트에 대한 질문이 있으면 다음 사이트를 방문하세요.
https://v1.test-utils.vuejs.org/guides/using-with-vuex.html
https://lmiller1990.github.io/vue-testing-handbook/vuex-in-components.html#using-createlocalvue-to-test-store-state

좋은 웹페이지 즐겨찾기