模拟安装钩 Jest 测试单元 [英] Mock mounted hook Jest testing unit
问题描述
我正在对组件进行一些单元测试.但是,在某些组件中,我在 mounted
钩子上运行了一些使我的测试失败的东西.我设法模拟了我不需要的方法.但是,我想知道是否有一种解决方法来模拟 mounted
钩子本身.
@/components/attendeesList.vue
<div><跨度>这是一个测试 </span>
</模板>
JS
Test.spec.js
import { mount,shallowMount } from '@vue/test-utils'从@/components/attendeesList.vue"导入测试describe('模拟一个方法', () => {test('是一个 Vue 实例', () => {const 包装器 = 浅安装(参加者列表,{测试方法:jest.fn(),})期望(wrapper.isVueInstance()).toBeTruthy()})
目前,vue-test-utils
不支持 mocking 生命周期钩子,但你可以模拟从 mounted
钩子调用的方法.在您的情况下,要模拟 testMethod()
,请使用 jest.spyOn
:
const testMethod = jest.spyOn(HelloWorld.methods, 'testMethod')const 包装器 = 浅安装(HelloWorld)期望(testMethod).toHaveBeenCalledWith(你好")
I am doing some unit testing for components. However, in some components, I have something running on the mounted
hook that is making my test fail.
I have managed to mock the methods that I do not need. However, I was wondering if there is a workaround mocking the mounted
hook itself.
@/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()
})
Currently, vue-test-utils
does not support mocking lifecycle hooks, but you can mock the method 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")
这篇关于模拟安装钩 Jest 测试单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!