有人可以向我解释为什么在测试中不能通过包装对象访问在methods
对象中传递给shallowMount
的模拟函数,而是必须通过首先创建一个变量来访问它。对模拟函数的引用?
我尝试了mount和shallowMount,创建/挂接了钩子,并且还通过直接调用函数来进行了尝试,而不是在创建/挂接的钩子内部。
// 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
}
}
}
答案 0 :(得分:1)
mount
或shallowMount
在这种情况下并不重要。 mount
表示测试将装入组件及其子组件,而shallowMount
仅装入组件并对其子组件存根。
您正在模拟setLoading
方法,这意味着您正在用模拟方法替换原始方法。就是说,调用setLoading
方法时,它不会运行组件中的代码,而是运行测试模型中的代码-在这种情况下为jest.fn()
。
模拟的目的是检查模拟方法是否被正确调用。
此外,wrapper.vm.setLoading
调用setLoading
方法。
答案 1 :(得分:0)
代替引用包装实例,您应该监视方法,例如:
const setLoading = jest.spyOn(wrapper.vm, 'setLoading');
expect(setLoading).toHaveBeenCalled() ;