有人可以向我解释为什么在 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
}
}
}
最佳答案
mount
或 shallowMount
在这种情况下并不重要。 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/