繁体   English   中英

我如何使用jest模拟外部类?

[英]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);

我不确定在这种情况下是什么以及我应该实际传入的内容。请注意我正在使用来自vue test utils的mount helper。

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

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

你的情况(也有其他的方法),你需要创建一个__mocks__相邻的文件夹node_modules之一,在创建文件__mocks__/lib/utils/index.js并导出嘲笑功能:

    export const moveTo = jest.fn()

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM