【问题标题】:How do you get the 'this' variable defined in a vuejs component unit test如何获得在 vuejs 组件单元测试中定义的“this”变量
【发布时间】:2017-08-26 08:30:37
【问题描述】:

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

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”。如何使它在单元测试上下文中工作?

【问题讨论】:

    标签: node.js unit-testing vue.js mocha.js mocha-webpack


    【解决方案1】:

    您正在调用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.testthis

    【讨论】:

    • 谢谢你修复它。我还需要从 'vue/dist/vue.js' 导入 vue 来编译模板,因为单元测试不在 .vue 文件中。
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2020-06-21
    • 1970-01-01
    • 2018-09-13
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多