unit-testing - Vue 单元测试 - 使用 vue-test-utils mount 时模拟导入的服务

标签 unit-testing vuejs2

我正在使用 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/

相关文章:

unit-testing - 如何检查称为 NSubstitute 的多个重载中的任何一个

vue.js - 为什么 vue.js 中的 setTimeout 有这种奇怪的行为?

javascript - Vue/Nuxt 异步元标记生成

vue.js - 将几个静态属性拉入 Vue.js

python - 我如何在 celery 中测试 on_failure

c++ - 使用 gtest 1.6 : how to check what is printed out? 进行单元测试

c# - 与数据库交互而不在数据库中创建数据的单元测试代码

vue.js - VueJS 应用程序是空白的

javascript - 所有循环值的总和 | Vuejs | Javascript |元素表

c# - 'Nancy.Bootstrapper.AppDomainAssemblyTypeScanner' 的类型初始值设定项引发异常