Open SetsuikiHyoryu opened 3 years ago
@SetsuikiHyoryu 感谢分享!
查到應該替換成爲:
如果能附带连接的话就最好了。
const mockFunction = jest.spyon(wrapper.vm, 'myFunction')
看起来这种写法跟下面应该是一样的
...
const mockFn = jest.fn();
wrapper.vm.myFunction = mockFn;
...
另外需要测试生命周期里面的函数的话,可以使用mixins混入,参考: https://github.com/holylovelqq/vue-unit-test-with-jest/issues/31#issuecomment-899243884
查到應該替換成爲:
import Sample from '@/views/Sample.vue' describe('test', () => { it('test function', async () => { const wrapper = shallmount(Sample) // TypeScript 下需要寫成 jest.spyon(wrapper.vm, 'myFunction' as any) const mockFunction = jest.spyon(wrapper.vm, 'myFunction') await wrapper.vm.myFunction() expect(mockFunction).toBeCalled() wrapper.destory() }) })
想请教下大佬: 这里如果我想触通过一个click事件来判断方法有没有被触发,就会报错: Error: expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called, but it was not called.
例如:
it('mutationsDecrement test', () => {
const mutationsMinus = wrapper.find('.mutationsMinus')
const mockMinus = jest.spyOn(wrapper.vm, 'mutationsDecrement')
mutationsMinus.vm.$emit('click')
expect(mockMinus).toHaveBeenCalled()
})
@sensen2500
Error: expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called.
这个报错很明显函数并没有被触发
mutationsMinus.vm.$emit('click')
我一般都是用mutationsMinus.trigger('click')
,你这种方法并没有试过,如果在其他的地方可以正常的话,就考虑看有没有正确获取DOM元素
参考:https://github.com/holylovelqq/vue-unit-test-with-jest/blob/master/01-vue-unit-test-with-jest/tests/unit/AppButton.spec.js#L64-L68 官方教程:https://test-utils.vuejs.org/api/#trigger
看了https://github.com/holylovelqq/vue-unit-test-with-jest/issues/37 貌似已经解决了。 还是说一下个人看法
jest.spyOn()
のNOTE有关 https://jestjs.io/zh-Hans/docs/jest-object#jestspyonobject-methodname --> 然而并没有证据jest.spyOn()
jest.fn()
@holylovelqq 请教一下大佬 关于 #37 按照上面评论写完依旧报错,烦请指点一下
Error: expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called.
Test2.vue
<template>
<div>
<!-- <button @click="increment">Click {{buttonValue}} {{innerCount}}</button> -->
<button @click="increment">{{innerCount}}</button>
</div>
</template>
<script>
export default {
data() {
return {
innerCount: 0,
};
},
methods: {
increment() {
this.innerCount += 1;
// this.$emit("add", this.innerCount);
},
},
};
</script>
Test2.spec.js
import {
mount,
shallowMount
} from '@vue/test-utils'
import Test2 from "@/components/Test2";
describe('Test for MyButton Component', () => {
it('calls increment when click on button', () => {
const wrapper = shallowMount(Test2)
const mockFn = jest.spyOn(wrapper.vm, 'increment')
const button = wrapper.find('button')
// 触发按钮的点击事件
button.trigger('click');
expect(mockFn).toBeCalled();
expect(mockFn).toHaveBeenCalledTimes(1)
})
})
查到應該替換成爲: