如何监视 fetch/middleware 方法的调度

how to spy on dispatch on fetch/middleware method

我正在尝试测试一个简单的页面

<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')
  })
})

但是还是不行,

有人可以帮我让它正常工作吗?

谢谢!

fetch是Nuxt特有的hook。 @vue/test-utils 不知道它,mockIndex 预计不会在测试中调用,除非显式调用挂钩。

应该是:

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

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