【问题标题】:How can I can a mock an external class using jest?如何使用 jest 模拟外部类?
【发布时间】:2019-08-10 10:49:10
【问题描述】:

我目前有以下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>

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

  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 测试工具中的挂载助手。

【问题讨论】:

    标签: javascript vue.js jestjs


    【解决方案1】:

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

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

    我又更新了以下行并添加了 wrapper.vm

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

    【讨论】:

      【解决方案2】:

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

      您可以通过创建"mocks/ subdirectory immediately adjacent to the 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"

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

          export const moveTo = jest.fn()
      

      【讨论】:

        猜你喜欢
        • 2022-06-30
        • 2018-01-18
        • 1970-01-01
        • 1970-01-01
        • 2018-01-21
        • 2017-09-30
        • 2019-10-09
        • 2019-10-27
        • 2020-09-09
        相关资源
        最近更新 更多