Programing

Vuex + Jest에서 스토어에 전화를 거는 게이터를 어떻게 유닛 테스트하는가?

c10106 2022. 4. 10. 23:11
반응형

Vuex + Jest에서 스토어에 전화를 거는 게이터를 어떻게 유닛 테스트하는가?

나는 내 vuex 상점에서 다음과 같은 아주 간단한 getter를 테스트하려고 한다.그것은 단순히 두 개의 줄을 연결시키는 것이다.

const getters = {
  adressToGet: state => {
    return state.baseAdress + store.getters.queryToGet
  }
 }

주의 부분을 조롱하는 것은 쉽지만 나는 가게를 조롱하는 좋은 방법을 찾을 수 없다.

구성 요소에 있는 경우 구성 요소를mount또는shallow모의 가게로 배정할 수도 있지만 그렇지 않아이건 Vuex 스토어에서 온 겁니다.

이건 내 시험 코드야.

import Search from '@/store/modules/search'

jest.mock('@/store/modules/search.js')

describe('search.js', () => {

  test('The adress getter gets the right adress', () => {
    const state = {
      baseAdress: 'http://foobar.com/'
    }
    // I define store here, but how can I inject it into my tested getter ?
    const store = { 
      getters: {
        queryToGet: 'barfoo'
      }
    }
    expect(Search.getters.adressToGet(state)).toBe('http://foobar.com/barfoo')
  })
})

알겠다http://foobar.com/undefined예상외로

이것을 하기 위한 가장 좋은 방법은 무엇인가?

편집: 첫 번째 주석에 이어 새 버전에도 동일한 결과가 표시됨:

import Search from '@/store/modules/search'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'

jest.mock('@/store/modules/search.js')

describe('search.js', () => {

  test('The adress getter gets the right adress', () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const mockState = {
      baseAdress: 'http://foobar.com/'
    }

    const store = new Vuex.Store({
      state: mockState,
      getters: {
        queryToGet: function () {
          return 'barfoo'
        }
      }
    }) 

   expect(Search.getters.adressToGet(mockState))
   .toBe('http://foobar.com/barfoo')
  })
})

많은 연구 끝에, 나는 제스트와 가게 의존도를 조롱해야 한다는 것을 깨달았다.이것은 그것을 하고 시험에 합격하는 올바른 방법인 것처럼 보인다.

import Search from '@/store/modules/search'

jest.mock('@/store/index.js', () =>({
  getters: {
    queryToGet: 'barfoo'
  }
}))

jest.mock('@/store/modules/search.js')

describe('search.js', () => {
  test('The adress getter gets the right adress', () => {
    const state = {
      baseAdress: 'http://foobar.com/'
    }
    expect(Search.getters.adressToGet(state))
    .toBe('http://foobar.com/barfoo')
  })
})

참조URL: https://stackoverflow.com/questions/49197867/in-vuex-jest-how-to-unit-test-a-getter-which-is-calling-the-store

반응형