vue.js - 模拟安装 Hook Jest 测试单元

标签 vue.js vuejs2 jestjs babel-jest vue-test-utils

我正在对组件进行一些单元测试。但是,在某些组件中,我在 mounted 上运行了一些东西。使我的测试失败的钩子(Hook)。
我设法模拟了我不需要的方法。但是,我想知道是否有模拟 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不支持模拟生命周期 Hook ,但您可以 mock the methodmounted 调用钩。在你的情况下,模拟 testMethod() , 使用 jest.spyOn :

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

关于vue.js - 模拟安装 Hook Jest 测试单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55746890/

相关文章:

vue.js - v-if 破坏 nuxt ssr

css - 从 Vuetify 中的可扩展数据表中删除框阴影

javascript - 我可以让 Vue.js 跨站点保持事件状态吗?

vue.js - vue-cli 解析 xlink :href in svgs when referenced in <img src ="">

node.js - 在 Vue.js 中找不到这些依赖项错误

javascript - 我如何使用 flexbox 和 Vue.js 将我在右侧发送的蓝色消息和我在左侧接收的黄色消息组合在一起?

vue.js - 为 element-ui 表设置行组件

javascript - 在 React 测试库中发现多个元素错误

javascript - 类型错误 : dispatch is not a function when I try to test a method using JEST

javascript - Jest/eslint 中函数缺少返回类型