programing

농담으로 vue 합성 함수를 조롱하는 방법

bestcode 2022. 8. 29. 22:13
반응형

농담으로 vue 합성 함수를 조롱하는 방법

graphql API를 요청하기 위해 vue2를 컴포지션 API, vuex 및 apollo 클라이언트와 함께 사용하고 있는데 합성 가능한 함수를 조롱할 때 문제가 발생함

// store-service.ts
export function apolloQueryService(): { 
  
  // do some graphql stuff

  return { result, loading, error };
}

// store-module.ts
import { apolloQueryService } from 'store-service'

export StoreModule {
  state: ()=> ({
    result: {}
  }),
  actions: {
    fetchData({commit}) {
      const { result, loading, error } = apolloQueryService()
      commit('setState', result);
    }
  },
  mutations: {
    setState(state, result): {
      state.result = result
    }
  }
}

테스트:

// store-module.spec.ts
import { StoreModule } from store-module.ts

const store = StoreModule 
describe('store-module.ts', () => {
  beforeEach(() => {
    jest.mock('store-service', () => ({
      apolloQueryService: jest.fn().mockReturnValue({ 
        result: { value: 'foo' }, loading: false, error: {} 
      })
    }))
  })

  test('action', async ()=> {
    const commit = jest.fn();
    await store.actions.fetchData({ commit });
    expect(commit).toHaveBeenCalledWith('setData', { value: 'foo' });
  })
}

커밋이 원래 apolloQueryService의 결과인 ('setData', {value:defined})로 호출되기 때문에 테스트가 실패합니다.내 모크가 작동하지 않는 것 같아.내가 뭘 잘못하고 있나요?도와주셔서 감사합니다!

언급URL : https://stackoverflow.com/questions/67998775/how-to-mock-vue-composable-functions-with-jest

반응형