你如何获得在vuejs组件unit testing中定义的“this”variables
我想在npm脚本中使用mocha-webpack来testing一个vuejs组件。 我在testing中嘲笑这样的vuex商店:
const vm = new Vue({ template: '<div><test></test></div>', store: new Vuex.Store(mockedStore), components: { 'test': TestItems } }).$mount()
我在组件上调用一个方法来testing,例如:
vm.$options.components.test.methods.foo()
在组件中,我有访问商店的代码,例如:
this.$store.commit('bar', data)
问题是,当它到达这一点,我得到这个错误:
'Cannot read property \'commit\' of undefined' undefined undefined
我证实在这方面“这个”是未定义的。 当我运行应用程序时,“this”被定义并且具有“$ store”。 我如何使它在unit testing环境中工作?
您正在调用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
forms被调用。