我怎样才能使用玩笑来模拟外部 class?

How can I can a mock an external class using jest?

我目前有以下 Vue 页面代码:

<template>
   // Button that when clicked called submit method
</template>

<script>
import { moveTo } from '@/lib/utils';

export default {
  components: {
  },
  data() {
  },
  methods: {
    async submit() {
      moveTo(this, COMPLETE_ACTION.path, null);
    },
  },
};
</script>

然后我有这个页面的测试文件。我的问题是我试图检查并断言使用 Jest 使用正确的参数调用了 moveTo 方法。它一直显示预期的未定义但收到了一个对象。以下是测试文件中的要点:

  import * as dependency from '@/lib/utils';
  dependency.moveTo = jest.fn();
  // I then trigger the button call which calls the submit method on the page
  expect(dependency.moveTo).toHaveBeenCalledWith(this, COMPLETE_ACTION.path, null);

我不确定 this 在这种情况下是什么以及我实际上应该传递什么。请注意我正在使用 vue test utils 的挂载助手。

您需要模拟模块本身。在您的情况下,您正在对一个从未调用过的间谍函数进行断言。

您可以通过创建 "mocks/ subdirectory immediately adjacent to the module". For a node module "If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the mocks directory adjacent to node_modules" 添加模块 mock。

在您的情况下(还有其他方法),您需要在 node_modules 文件夹旁边创建一个 __mocks__ 文件夹,并在 __mocks__/lib/utils/index.js 中创建一个文件并导出模拟函数:

    export const moveTo = jest.fn()

我解决了我的问题,它是测试中的 this 参数。 在测试中未定义,期望与 VueComponent 匹配。

我使用了包装器,然后根据文档通过引用虚拟机 属性 访问了 VueComponent:https://vue-test-utils.vuejs.org/api/wrapper/#properties

反过来,我更新了以下行并添加了 wrapper.vm

  expect(dependency.moveTo).toHaveBeenCalledWith(wrapper.vm, COMPLETE_ACTION.path, null);