模拟挂载钩子的Jest测试单元

9

我正在对组件进行单元测试。然而,在某些组件中,我有一些在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()
})
2个回答

9

目前,vue-test-utils不支持模拟生命周期钩子,但是你可以从mounted钩子中调用的方法进行模拟。对于你的情况,如果想要模拟testMethod(),请使用jest.spyOn

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

0

Vue测试工具有一种内置的方式来模拟方法 -

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

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


现在桩化还不晚吧?因为挂载钩子会在获取存根之前运行? - heyr
当使用shallowMount通过模拟方法时,这些方法会在mounted钩子被调用之前被覆盖。 - Alon Bar David
你能检查一下我的更新帖子吗?老实说,我得到了完全相同的错误。 我做错了什么? - heyr
从2021年开始,vue-test-utils不再支持替换方法。 - Matt Sanders

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接