Vue 单元测试 - 使用 vue-test-utils mount 时模拟导入的服务 [英] Vue unit testing - mocking imported services when using vue-test-utils mount

查看:75
本文介绍了Vue 单元测试 - 使用 vue-test-utils mount 时模拟导入的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vue-test-utils 中的 mount(),有一个组件可以导入应该在单元测试中模拟的服务.

I'm playing with mount() from vue-test-utils, have a component that imports services that should be mocked in the unit test.

我看到 mount() 有一个模拟选项,但试图推断 指南、常见提示、模拟注入到注入服务的场景让我望而却步.

I see that mount() has a mocks option, but trying to extrapolate the example given at guides, common-tips, mocking injections to the scenario of an injected service is eluding me.

mount(Component, {
  mocks: {
    ...?
  }
})

组件只是简单的导入服务,就是纯JS

The component simply imports the service, which is plain JS

import DataService from '../services/data.service'

我可以使用这里详细介绍的注入加载器来让它工作 使用模拟测试

I can get it working using the inject-loader which is detailed here 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 传递给它吗?

Since mount() has a mocks option, should it not be possible to pass mockedServices to it in some form?

推荐答案

mocks 指的是 Vue 实例.您正在尝试模拟文件依赖项,这是一个不同的问题.正如您所说,一种解决方案是注入加载器.另一个是 babel-plugin-rewire.

mocks refers to the Vue instance. You're trying to mock a file dependency, which is a different problem. As you said, one solution is inject-loader. Another is the babel-plugin-rewire.

让我弄清楚 mocks 选项的作用.

Let me clear up what the mocks option does.

mocks 向 Vue 实例添加属性.

mocks adds properties to the Vue instance.

如果你有一个注入 $route 的应用,你可能有一个试图访问它的组件:this.$route.path:

If you have an app that injects $route, you might have a component that tries to access it: this.$route.path:

...
  methods: {
    logPath() {
      console.log(this.$route.path)
    }
  } 
... 

如果你在没有安装 Vue router 的情况下尝试 mount 这个组件,它会抛出一个错误.要解决这个问题,您可以使用 mocks 挂载选项将模拟 $route 对象注入 Vue 实例:

If you try to mount this component without installing Vue router, it will throw an error. To solve this, you can use the mocks mount option to inject a mock $route object to the Vue instance:

const $route = { path: 'some/mock/value' }
mount(Component, {
  mocks: {
    $route
  }
})

这篇关于Vue 单元测试 - 使用 vue-test-utils mount 时模拟导入的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆