模拟安装钩 Jest 测试单元

hey*_*red 5 vue.js jestjs babel-jest vuejs2 vue-test-utils

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

@/components/attendeesList.vue

<template>
  <div>
    <span> This is a test </span> 
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

JS

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

mounted: {
    this.testMethod();
}
</script>
Run Code Online (Sandbox Code Playgroud)

测试规范.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()
})
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 5

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

const testMethod = jest.spyOn(HelloWorld.methods, 'testMethod')
const wrapper = shallowMount(HelloWorld)
expect(testMethod).toHaveBeenCalledWith("hello")
Run Code Online (Sandbox Code Playgroud)