【问题标题】:Cannot spyOn functions inside of Vue 3 setup()无法在 Vue 3 setup() 中监视函数
【发布时间】:2021-02-09 02:51:59
【问题描述】:

如何使用 Jest 编写一个调用 resetTimer 并检查 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 |     });

谢谢!

【问题讨论】:

  • 好问题,让我想知道模拟和间谍如何在合成函数中发挥作用。也许您可以在测试中替换组件上的setup,在它返回之前执行spy

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多