programing

vuex 작업에서 api 호출을 조롱하는 행위

prostudy 2022. 5. 21. 08:53
반응형

vuex 작업에서 api 호출을 조롱하는 행위

나는 액션이 있는 vuex 상점을 가지고 있다.

//actions.js
import api from '@/api.js'

export default {
  getAllProducts ({commit}) {
    // call the api and return a promise with the products

    api.fetchAllProducts().then((products) => {
        commit('getAllProducts', products)
    })  
}

이제 시험해 보자!

// actions.spec.js
import actions from './actions.js'
import api from './api.js'

describe('shop actions', () => {

  it('calls api and fetches products', () => {
    let state = {items: []}
    let commit = sinon.spy()
    let stub = sinon.stub(api, 'fetchAllProducts')
    stub.resolves('a product')

    actions.getAllProducts({commit, state})

    expect(commit.args).to.deep.equal([
        ['SET_ALL_PRODUCTS', 'a product']
    ])  
  })
})

이것은 지금까지 내가 시도한 것이다.그것은 몇 가지 이유 때문에 작동하지 않는다.

  1. api 함수의 sinon stub도 actions.js에 대해 가져온 api를 스텁하지 않는다.
  2. api 함수는 약속을 반환하므로, 해결되기를 기다리는 대신 테스트는 주장을 반환하므로 commit.args는 항상 [ ]이 될 것이다.

vuex 액션을 테스트할 수 있는 방법에 대한 조언.api 모듈을 스텁하는 것이 가장 큰 어려움이라고 생각하는데, 나는 꼼짝도 못한다.어떤 조언이라도 감사하게 생각한다 :)

액션getAllProducts약속을 이행해야 한다.

getAllProducts ({ commit }) {
  return api.fetchAllProducts().then((products) => {
    commit('SET_ALL_PRODUCTS', products)
  })
}

그러면 테스트 코드는 다음과 같아야 한다.

describe('shop actions', () => {
 it('calls api and fetches products', done => {
   let state = {items: []}
   let commit = sinon.spy()
   let stub = sinon.stub(api, 'fetchAllProducts')
   stub.resolves('a product')

   actions.getAllProducts({commit, state}).then(() => {
     expect(commit.args).to.deep.equal([
       ['SET_ALL_PRODUCTS', 'a product']
     ])
     done()
    })
   stub.restore()
   })
})

또한, 만약 당신이 행동에서 약속을 지키지 않는다면 우리는 비동기/와이트를 사용할 수 있다.

 it('calls api and fetches products', async () => {
   let state = {items: []}
   let commit = sinon.spy()
   let stub = sinon.stub(api, 'fetchAllProducts')
   stub.resolves('a product')

   await actions.getAllProducts({commit, state})
   expect(commit.args).to.deep.equal([
       ['SET_ALL_PRODUCTS', 'a product']
     ])
   stub.restore()
 })

참조URL: https://stackoverflow.com/questions/50222851/mocking-api-call-in-vuex-action

반응형