Тест vue компонент с функцией setTimeout в Jest - PullRequest
0 голосов
/ 28 мая 2020

Я пытаюсь протестировать функцию debounce с setTimeout. Это вход с вызовом ajax api. Я пробовал jest.useFakeTimers () и jest.runAllTimers (), но безуспешно. Я также попытался запустить jest.advanceTimersByTime (501) - потому что мой тайм-аут составляет 500 мс, но все равно не повезло.

Компонент формы:

<template>
  <div>
    <div class="columns">
      <div class="column">
        <b-field :label="`${$t('categories')}`" label-for="categories">
          <b-taginput
            id="categories"
            v-model="categories"
            :data="filteredCategories"
            :autocomplete="true"
            :allow-new="false"
            :open-on-focus="false"
            icon="label"
            @typing="getFiltered"
          >
          </b-taginput>
        </b-field>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  Ref,
  toRefs
} from '@vue/composition-api'
import CategoriesRepository from '~/repository/categories'

export default defineComponent({
  props: {
    product: {
      type: any,
      default: () => {}
    }
  },
  setup(props, context) {
    const CategoriesAPI = new CategoriesRepository(context.root.$store)
    const timeout: any = null

    const state = reactive({
      categories: [],
      filteredCategories: [],
      // needed to debounce search
      searchTimeout: timeout
    })

    const getCategories = () => {
      CategoriesAPI.all()
        .then((response) => response.json())
        .then((data) => {
          state.categories = data
        })
        .catch(() => {
          state.categories = []
        })
    }
    const getFiltered = (search: string) => {
      clearTimeout(state.searchTimeout)
      // lines above are not reached by code coverage
      state.searchTimeout = setTimeout(() => {
        if (search.length > 0) {
          CategoriesAPI.search(search)
            .then((response) => response.json())
            .then((data) => {
              state.filteredCategories = data
            })
            .catch(() => {
              state.filteredCategories = []
            })
        }
      }, 500)
    }
    return {
      ...toRefs(state),
      getFiltered
    }
  }
})
</script>

и Form.spe c. ts:

import { createLocalVue, mount } from '@vue/test-utils'
import CompositionApi from '@vue/composition-api'
import Buefy from 'buefy'
import mockFetch from '@/test'
import Form from '@/components/products/Form.vue'

const localVue = createLocalVue()
localVue.use(CompositionApi)
localVue.use(Buefy)

describe('Categories in product form', () => {
  jest.useFakeTimers()
  test('Test getting categories', async () => {
    const wrapper = mount(Form, {
      localVue
    })
    const fake_categories = ['test', 'food', 'travel']
    // upload fetch
    // it should be called only by getFiltered
    window.fetch = mockFetch(200, fake_categories)
    wrapper.find('#categories').setValue('test')
    wrapper.find('#categories').trigger('change')
    jest.runAllTimers()
    // then I see in code coverage that state.searchTimeout = setTimeout(()... was not called.
  })

и mockFetch:

function mockFetch(status: number, data: any) {
  return jest.fn().mockImplementation(() =>
    Promise.resolve({
      ok: true,
      status: status,
      json: () => data
    })
  )
}
...