M
M
MarkSexton2021-02-11 13:21:15
Vue.js
MarkSexton, 2021-02-11 13:21:15

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>


store.js
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)
        })
    )
  },


Component.spec.js
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)
  })
})


After running the test case, I get the following:
console.log
    VueWrapper {
      isFunctionalComponent: undefined,
      _emitted: [Object: null prototype] {},
      _emittedByOrder: [] }


What is the problem? When I mock the data directly in the component's data , the test works, but I can't mock the data in the test...

Thank you for your attention.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Vasilev, 2021-02-11
@Nolis

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 question

Ask a Question

731 491 924 answers to any question