【发布时间】:2020-01-02 11:28:54
【问题描述】:
有人可以向我解释为什么在methods 对象中传递给shallowMount 的模拟函数不能通过包装对象在测试中访问,而是必须首先创建一个变量作为对模拟函数?
我已经尝试了 mount 和 shallowMount,created/mounted hooks 以及直接调用函数而不是 created/mounted 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
}
}
}
【问题讨论】:
-
如果我将
setLoading: setLoadingMock替换为setLoading: () => {},也会遇到同样的问题
标签: vue.js jestjs vue-test-utils