Cha*_*eau 5 vue.js jestjs spyon vuejs3 vue-composition-api
如何使用 Jest 编写调用resetTimer并检查startTimer也被调用的测试?
代码:
setup () {
const startTimer = () => {
// ...
};
const resetTimer = () => {
startTimer();
};
return {
startTimer,
resetTimer
}
Run Code Online (Sandbox Code Playgroud)
测试:
import { shallowMount } from '@vue/test-utils';
import Overlay from '@/components/Overlay.vue';
const wrapper = shallowMount(Overlay);
it('resetTimer should call startTimer', () => {
const spy = jest.spyOn(wrapper.vm, 'resetTimer');
wrapper.vm.startTimer();
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
结果:
TypeError: object.hasOwnProperty is not a function
187 |
188 | it('resetTimer should call startTimer', () => {
> 189 | const spy = jest.spyOn(wrapper.vm, 'resetTimer');
| ^
190 | wrapper.vm.startTimer();
191 | expect(spy).toHaveBeenCalled();
192 | });
Run Code Online (Sandbox Code Playgroud)
谢谢!
小智 -2
找到了一个临时解决方案,不是最好的,但至少可以让您检查它是否调用了该函数。
import { mount } from '@vue/test-utils';
import Component from './Component.vue';
describe('Component', () => {
it('should call foo', () => {
Component.created = function () {
this.foo = jest.fn(this.foo);
};
const component = mount(Component);
component.find('div').trigger('click');
component.vm.foo();
expect(component.vm.foo).toHaveBeenCalled();
delete Component.created;
});
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |