我正在使用 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
}
})
关于unit-testing - Vue 单元测试 - 使用 vue-test-utils mount 时模拟导入的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553779/