unit-testing之Vue 单元测试之使用 vue-test-utils mount 时模拟导入的服务
langtianya
阅读:170
2025-01-19 22:14:33
评论:0
我正在使用 vue-test-utils 中的 mount(),有一个组件可以导入应该在单元测试中模拟的服务。
我看到 mount() 有一个 mocks 选项,但试图推断 guides, common-tips, mocking injections 给出的示例注入(inject)服务的场景让我望而却步。
mount(Component, {
mocks: {
...?
}
})
组件只是简单的导入服务,就是普通的 JS
import DataService from '../services/data.service'
我可以使用此处详细介绍的注入(inject)加载器使其工作 Testing With Mocks
有效的代码
const MyComponentInjector = require('!!vue-loader?inject!./MyComponent.vue')
const mockedServices = {
'../services/data.service': {
checkAll: () => { return Promise.resolve() }
},
}
const MyComponentWithMocks = MyComponentInjector(mockedServices)
const wrapper = mount(MyComponentWithMocks, { store: mockStore, router })
mount(MyComponent, { mocks: ... }) 的语法是什么?
既然 mount() 有一个 mocks 选项,难道不能以某种形式将 mockedServices 传递给它吗?
请您参考如下方法:
mocks
指的是 Vue 实例。您正在尝试模拟文件依赖项,这是一个不同的问题。正如您所说,一种解决方案是注入(inject)加载器。另一个是 babel-plugin-rewire。
让我澄清一下 mocks
选项可以。mocks
向 Vue 实例添加属性。
如果您有一个注入(inject) $route
的应用程序,您可能有一个组件试图访问它:this.$route.path
:
...
methods: {
logPath() {
console.log(this.$route.path)
}
}
...
如果您尝试
mount
这个组件没有安装Vue路由器,会报错。要解决此问题,您可以使用
mocks
用于注入(inject)模拟的挂载选项
$route
Vue 实例的对象:
const $route = { path: 'some/mock/value' }
mount(Component, {
mocks: {
$route
}
})
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。