gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:37:38 27 4
gpt4 key购买 nike

我正在对组件进行一些单元测试。但是,在某些组件中,我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com