반응형
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']
])
})
})
이것은 지금까지 내가 시도한 것이다.그것은 몇 가지 이유 때문에 작동하지 않는다.
- api 함수의 sinon stub도 actions.js에 대해 가져온 api를 스텁하지 않는다.
- 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
반응형
'programing' 카테고리의 다른 글
vuej의 글로벌 구성 요소로 데이터 전달 (0) | 2022.05.21 |
---|---|
사용자 정의 글꼴 및 XML 레이아웃(Android) (0) | 2022.05.21 |
(VueJS) Vuex Getter는 다른 모듈 상태 변경을 기반으로 업데이트되어야 함 (0) | 2022.05.21 |
Vue.js 독립 실행형에서 핸즈통트 가능 (0) | 2022.05.21 |
"비교 방식은 일반 계약을 위반한다!" (0) | 2022.05.21 |