模拟挂钩 Jest 测试单元

Mock mounted hook Jest testing unit

我正在对组件进行一些单元测试。但是,在某些组件中,我在 mounted 挂钩上有一些东西 运行 导致我的测试失败。 我设法模拟了我不需要的方法。但是,我想知道是否有模拟 mounted 挂钩本身的解决方法。

@/components/attendeesList.vue

<template>
  <div>
    <span> This is a test </span> 
  </div>
</template>

JS

<script>
methods: {
    testMethod: function() {
        // Whatever is in here I have managed to mock it
    }
},

mounted: {
    this.testMethod();
}
</script>

Test.spec.js

import { mount, shallowMount } from '@vue/test-utils'
import test from '@/components/attendeesList.vue'

describe('mocks a method', () => {    
  test('is a Vue instance', () => {
  const wrapper = shallowMount(attendeesList, {
    testMethod:jest.fn(),
  })
  expect(wrapper.isVueInstance()).toBeTruthy()
})

Vue test utils 有一个内置的方法来模拟方法 -

const wrapper = shallowMount(attendeesList,{
   testMethod:jest.fn()
})

解决您的问题的最简单方法是将已安装挂钩中的代码移动到一个方法中,使用上面的代码存根并从您的挂钩中调用它。

目前,vue-test-utils 不支持模拟生命周期挂钩,但您可以 called from the mounted hook. In your case, to mock testMethod(), use jest.spyOn:

const testMethod = jest.spyOn(HelloWorld.methods, 'testMethod')
const wrapper = shallowMount(HelloWorld)
expect(testMethod).toHaveBeenCalledWith("hello")