Answer the question
In order to leave comments, you need to log in
How to test API call action in mounted?
Hello! Faced the problem of the following plan: - it is necessary to write a unit test of the component that will dispatch the data by calling the storage action, which in turn makes an API call .
The problem is that when mounting the component - returns undefined
Component.vue
<template>
<div>
<ul v-for="item in array" :key="item.id">
<li>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Component',
data() {
return {
array: []
}
},
mounted() {
this.$store.dispatch('ACTION').then(data => {
this.array = data
})
}
}
</script>
ACTION() {
return this.$axios
.get('/api/url')
.then(response => {
if (Object.prototype.hasOwnProperty.call(response, 'error')) {
return false
}
return response.data
})
.catch(error => {
this.$sentry.captureException(error)
})
)
},
import { mount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import Regions from './Components'
const localVue = createLocalVue()
const array = [
{
name: 'Москва'
},
{
name: 'Cанкт-Петербург'
},
{
name: 'Нижний Новгород'
}
]
localVue.use(Vuex)
describe('component тест', () => {
let actions
let store
beforeEach(() => {
actions = {
ACTION: jest.fn()
}
actions.ACTION.mockReturnValue(array)
store = new Vuex.Store({
actions
})
})
it('верно отрисовывается по полученным данным', () => {
const wrapper = mount(Component, { store, localVue })
console.log(wrapper)
})
})
console.log
VueWrapper {
isFunctionalComponent: undefined,
_emitted: [Object: null prototype] {},
_emittedByOrder: [] }
Answer the question
In order to leave comments, you need to log in
set up the ACTIONS -> MUTATIONS -> GETTERS chain, after executing your request in mounted, drag the data from the getter to computed, it should save the situation
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question