W
W
Wayne12121212020-09-16 12:26:43
JavaScript
Wayne1212121, 2020-09-16 12:26:43

What are jest mocks used for?

Hello everyone

. There is a Foo component.

<template>
  <button @click="fetchResults" />
</template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        value: null
      }
    },

    methods: {
      async fetchResults() {
        const response = await axios.get('mock/service')
        this.value = response.data
      }
    }
  }
</script>


Test for the Foo component
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo'
jest.mock('axios') //что значит эта строчка и что она делает?

it('делает асинхронный запрос при нажатии кнопки', done => {
  const wrapper = shallowMount(Foo)
  wrapper.find('button').trigger('click')
  wrapper.vm.$nextTick(() => { //код грузится 5 секунд и тесты обрываются
    expect(wrapper.vm.value).toBe('value')
    done()
  })
})


The example is taken from the documentation

. As a result, I do not understand what is the meaning of the jest.mock('axios') line when we try to pull the real request from the component, which in the end does not work.
Tell me how it works? I've been trying for the 3rd day and I can't find anything ((

Thanks a lot in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-09-16
@Wayne1212121

After and before there should be a line In someMockData you are passing fake data that axios should return instead of a real request to the server. If you need real data from the server, the line is not needed
jest.mock('axios')
wrapper.find('button').trigger('click')
axios.get.mockResolvedValue(someMockData);
jest.mock('axios')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question