我正在对组件进行一些单元测试。但是,在某些组件中,我在 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 method从 mounted
调用钩。在你的情况下,模拟 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/