как шпионить за отправкой методом выборки / промежуточного программного обеспечения - PullRequest
0 голосов
/ 18 июня 2020

Я пытаюсь протестировать простую страницу

<template>
  <HomeTemplate />
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  async fetch(context) { // or middleware(context)
    await context.store.dispatch('categories/index')
  }
})
</script>

Я хотел бы проследить за отправкой и узнать, все ли прошло идеально, поэтому я попробовал, но сначала я попытался подсмотреть только за действием:

import { Wrapper, shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex, { Store } from 'vuex'
import HomePage from './index.vue'
import { CategoriesState } from '@/store/categories'

const localVue = createLocalVue()
localVue.use(Vuex)

describe('HomePage', () => {
  type Instance = InstanceType<typeof HomePage>
  let wrapper: Wrapper<Instance>

  let store: Store<CategoriesState>

  const mockIndex: jest.Mock = jest.fn()

  beforeAll(() => {
    store = new Vuex.Store({
      modules: {
        categories: {
          namespaced: true,
          actions: { index: mockIndex }
        }
      }
    })

    wrapper = shallowMount(HomePage, {
      stubs: ['HomeTemplate'],
      localVue,
      store
    })
  })

  it('should call vuex action to fetch categories', () => {
    expect(mockIndex).toHaveBeenCalledWith('categories/index')
  })
})

учитывая, что метод fetch() или middleware() получает nuxt context , я попытался имитировать

import { Wrapper, shallowMount } from '@vue/test-utils'
import HomePage from './index.vue'

describe('HomePage', () => {
  type Instance = InstanceType<typeof HomePage>
  let wrapper: Wrapper<Instance>

  const mockIndex: jest.Mock = jest.fn()

  beforeAll(() => {
    wrapper = shallowMount(HomePage, {
      stubs: ['HomeTemplate'],
      mocks: {
        context: {
          store: {
            dispatch: mockIndex
          }
        }
      }
    })
  })

  it('should call vuex action to fetch categories', () => {
    expect(mockIndex).toHaveBeenCalledWith('categories/index')
  })
})

, но он все равно не работает , enter image description here

Может ли кто-нибудь помочь мне заставить его работать правильно?

спасибо!

1 Ответ

0 голосов
/ 18 июня 2020

fetch - это ловушка, c специфичная для Nuxt. @vue/test-utils не знает об этом, mockIndex не ожидается, что он будет вызван в тестах, если только ловушка не вызывается явно.

Это должно быть:

const context = {
  store: {
    dispatch: mockIndex
  }
};

await HomePage.options.fetch(context);
expect(mockIndex).toBeCalledWith(...)
...