vue.js - 使用 Vue Test Utils 将模拟方法传递给 mount/shallowMount

标签 vue.js jestjs vue-test-utils

有人可以向我解释为什么在 methods 中传递了一个模拟函数反对 shallowMount不能通过包装器对象在测试中访问,而必须通过首先创建一个变量作为对模拟函数的引用来访问?

我已经尝试过 mount 和shallowMount,创建/安装的钩子(Hook),也通过直接调用函数而不是在创建/安装的钩子(Hook)内部。

// TestComponent.spec.js

import TestComponent from '@/components/TestComponent'
import { shallowMount, createLocalVue } from '@vue/test-utils'

const localVue = createLocalVue()

const setLoadingMock = jest.fn() // mock function that is accessible in the test

function createWrapper () {

  const defaultMountingOptions = {
    localVue,
    methods: {
      setLoading: setLoadingMock
    }
  }

  return shallowMount(TestComponent, defaultMountingOptions)
}

describe('TestComponent.vue', () => {

  let wrapper

  beforeEach(() => {
    wrapper = createWrapper()
  });

  it('will call setLoading', () => {
    expect(wrapper.vm.setLoading).toHaveBeenCalled() 
    // FAILS. Console message:
    // Matcher error: received value must be a mock or spy function

    // Received has type:  function
    // Received has value: [Function bound mockConstructor]
  })

  it('will call setLoading', () => {
    expect(setLoadingMock).toHaveBeenCalled() // PASSES
  })
})
TestComponent.vue

export default {
  name: 'TestComponent',
  mounted () {
    this.setLoading()
  },

  methods: {
    setLoading () {
      console.log('Original method'); // Never logs
    }
  }
}

最佳答案

mountshallowMount在这种情况下并不重要。 mount意味着 test 将挂载组件及其子组件,而 shallowMount将仅挂载组件并 stub 其子组件。

你在 mock setLoading方法,这意味着您正在用模拟替换原始方法。意思是,当 setLoading方法被调用,它不会运行来自你的组件的代码,而是来自测试模拟的代码 - 在这种情况下 jest.fn() .

模拟的目的是检查被模拟的方法是否被正确调用。

另外,wrapper.vm.setLoading调用 setLoading方法。

关于vue.js - 使用 Vue Test Utils 将模拟方法传递给 mount/shallowMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57705907/

相关文章:

javascript - VueJS 是否保证以正确的顺序调用 mounted() ?

javascript - Jest - 未导出的模拟函数

react-native - 使用 Jest 模拟时找不到模块 'NativeAnimatedHelper'

Vue.js:是否可以使用 Vue 项目执行 "Conditional compilation"?

html - 输入字段接受任何字符,忽略正则表达式

typescript - 如何用 Jest 测试 void 异步函数是否成功?

typescript - 使用 Jest 测试 Vuejs 和 TypeScript 会导致错误 "Property ' xxx' does not exist on type 'CombinedVueInstance'

vue.js - 使用 Vue Test Utils,如何检查按钮是否被禁用?

vue.js - 如何测试自定义输入 Vue 组件

vue.js - Vuex Store 是否可以从控制台或客户端浏览器访问?