vue.js - 无法在 Vue 3 setup() 中监视函数

标签 vue.js jestjs vuejs3 vue-composition-api spyon

如何使用调用 resetTimer 的 Jest 编写测试并检查 startTimer也被调用?
代码:

setup () {
    const startTimer = () => {
        // ...
    };

    const resetTimer = () => {
        startTimer();
    };

    return {
        startTimer,
        resetTimer
    }
测试:
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();
});
结果:
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 |     });
谢谢!

最佳答案

找到了一个临时解决方案,不是最好的,但至少可以让您检查是否调用了它的函数。

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;
  });
});

关于vue.js - 无法在 Vue 3 setup() 中监视函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64544061/

相关文章:

javascript - 难以重定向到 404 页面

file - 如何重置/清除文件输入

vuejs3 - 如何使对象在 Vue 3 中作为 Prop 传递?

vue.js - 如何创建导入另一个组件的 Vue 包

vuejs3 - 如何从 Storybook 故事访问 Vue3 应用程序实例?

javascript - 运行构建 :electron in Vue CLI 3? 后,如何将静态 config.json 文件中的值读取到 Vue 文件中的 TypeScript

javascript - 如何在 Vue.js 中测试计算属性?无法模拟 "data"

unit-testing - 当预期/接收值是对象时,Jest.js 测试不会通过

javascript - 用 TypeScript 开 Jest

reactjs - 开 Jest 测试: custom currency/decimal formatters showed wrong delimiters