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

1

2

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

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?

Outermost answered 1/4, 2017 at 0:10 Comment(0)
N
1

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 will be called with vm.$refs.test as this.

N answered 1/4, 2017 at 0:15 Comment(1)
Thank you that fixed it. I also needed to import vue from 'vue/dist/vue.js' to get the template to compile since the unit test is not in a .vue file.Outermost

© 2022 - 2024 — McMap. All rights reserved.