如何获取vuejs组件单元测试中定义的'this'变量

How do you get the 'this' variable defined in a vuejs component unit test

我正在尝试在 npm 脚本中使用 mocha-webpack 来测试 vuejs 组件。我在测试中像这样模拟 vuex store:

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

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

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

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

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

问题是当它到达这一点时我得到这个错误:

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

我确认 'this' 在此上下文中未定义。当我 运行 应用程序时,'this' 被定义并具有“$store”。我怎样才能让它在单元测试上下文中工作?

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

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