如何获得在Vue.js组件单元测试中定义的'this'变量 [英] How do you get the 'this' variable defined in a vuejs component unit test

查看:534
本文介绍了如何获得在Vue.js组件单元测试中定义的'this'变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在npm脚本中使用mocha-webpack来测试vuejs组件.我在测试中嘲笑vuex商店:

I am trying to use mocha-webpack in an npm script to test a vuejs component. I am mocking the vuex store like this in the test:

const vm = new Vue({
        template: '<div><test></test></div>',
        store: new Vuex.Store(mockedStore),
        components: {
            'test': TestItems
        }
    }).$mount()

我在组件上调用一个方法进行测试,例如:

I call a method on the component to test such as:

vm.$options.components.test.methods.foo()

在组件中,我具有访问商店的代码,例如:

In the component I have code that accesses the store such as:

this.$store.commit('bar', data)

问题是,到了这一点,我得到了这个错误:

The problem is when it gets to this point I get this error:

'Cannot read property \'commit\' of undefined' undefined undefined

我验证了"this"在此上下文中未定义.当我运行应用程序时,定义了"this"并具有"$ store".如何使其在单元测试环境中起作用?

I verified that 'this' is undefined in this context. When I run the app, 'this' is defined and has '$store'. How can I make it work in the unit test context?

推荐答案

您正在调用test组件的foo方法,而没有test实例.尝试做这样的事情:

You're calling the foo method of the test component without an instance of test. Try doing something like this:

const vm = new Vue({
  template: '<div><test ref="test"></test></div>',
  store: new Vuex.Store(mockedStore),
  components: {
    'test': TestItems
  }
}).$mount()

vm.$refs.test.foo()

foo将以vm.$refs.test作为this调用.

这篇关于如何获得在Vue.js组件单元测试中定义的'this'变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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