【问题标题】:Mock mounted hook Jest testing unit模拟安装挂钩 Jest 测试单元
【发布时间】:2019-09-08 20:12:27
【问题描述】:

我正在对组件进行一些单元测试。但是,在某些组件中,我在 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.js vuejs2 jestjs babel-jest vue-test-utils


    【解决方案1】:

    目前,vue-test-utils 不支持模拟生命周期钩子,但您可以从 mounted 钩子调用 mock the method。在您的情况下,要模拟 testMethod(),请使用 jest.spyOn

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 存根不会太晚吗?由于挂载的钩子在获得存根之前运行?
      • 当通过 shallowMount 使用模拟方法时,这些方法在调用挂载钩子之前被覆盖。
      • 你能检查一下我更新的帖子吗?老实说,我得到了完全相同的错误。我做错了什么?
      • 自 2021 年起 vue-test-utils 不再支持替换方法
      猜你喜欢
      • 2021-10-13
      • 2023-01-24
      • 2021-07-17
      • 2016-02-11
      • 2021-11-05
      • 1970-01-01
      • 2021-04-17
      • 2018-12-28
      • 1970-01-01
      相关资源
      最近更新 更多