1

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

我不确定在这种情况下是什么以及我实际上应该传递什么。请注意我正在使用来自 vue 测试工具的挂载助手。

4

2 回答 2

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);
于 2019-03-19T20:40:04.217 回答
0

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

您可以通过创建与模块紧邻的mocks /子目录”来添加模块模拟。对于节点模块如果您要模拟的模块是节点模块(例如:lodash),则模拟应放置在与 node_modules 相邻的模拟目录

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

    export const moveTo = jest.fn()
于 2019-03-19T20:00:24.300 回答