如何存根 Vue 组件方法进行单元测试 [英] How to stub Vue component methods for unit testing

查看:112
本文介绍了如何存根 Vue 组件方法进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Vue 单文件组件中存根某些方法(特别是 getter)以使用 mocha/expect 进行单元测试?

How can I stub certain methods (getters, in particular) from Vue single file components for unit testing with mocha/expect?

我面临的问题如下:我有一个带有 get 方法的组件 someData

The problem I was facing was the following: I have a component with a get method someData

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import SomeService from '@/services/some.service'

@Component()
export default class MyApp extends Vue {
    ...

    mounted () {
      ...
    }

    get someData () {
      return this.$route.path.split('/')[1] || 'main'
    }

    get getLocation () {
      return this.someService.getBaseURL()
    }

    initSomeStringProperty (): string {
      return 'some string'
    }
}
</script>

我的测试总是失败:

[Vue 警告]:渲染错误:TypeError:无法读取未定义的属性‘路径’"

[Vue warn]: Error in render: "TypeError: Cannot read property 'path' of undefined"

当我尝试使用 sinon 存根方法时,如下所示:

When I try to stub the method using sinon, like following:

describe('MyApp.vue', () => {
  if('returns main', () => {
    const dataStub = sinon.stub(MyApp, 'someData')
    listStub.yields(undefined, 'main')
    const wrapper = shallowMount(AppNavBar)
    expect(wrapper.text()).to.include('Some Content')
  })
})

但是,我收到以下错误:

However, I get the following error:

TypeError: 不能存根不存在的自己的属性 someData

TypeError: Cannot stub non-existent own property someData

此外,对于其他所有方法,我都会遇到相同的错误,我想类似地存根,例如 initSomeStringProperty().

In addition, I get the same error for every other method, I want to stub analogously, e.g., initSomeStringProperty().

推荐答案

你可以设置组件的 挂载时计算props和方法,如下图.更新:从 1.x 开始,设置方法已经已弃用 支持存根(请参阅 @EstusFlask 的答案,了解如何正确存根与诗乃).

You could set the component's computed props and methods upon mounting, as shown below. Update: As of 1.x, setting methods has been deprecated in favor of stubbing (see @EstusFlask's answer on how to properly stub with Sinon).

const wrapper = shallowMount(MyApp, {
  computed: {
    someData: () => 'foo'
  },
  methods: {
    initSomeStringProperty: () => 'bar'
  }
})
expect(wrapper.vm.someData).to.equal('foo')
expect(wrapper.vm.initSomeStringProperty()).to.equal('bar')

如果您只是想避免 $route 未定义的错误,您可以mock $route 挂载:

If you were just trying to avoid the error about $route being undefined, you could mock $route upon mounting:

const wrapper = shallowMount(MyApp, {
  mocks: {
    $route: { path: '/home' }
  }
})
expect(wrapper.vm.someData).to.equal('home')

这篇关于如何存根 Vue 组件方法进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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