如何获得在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
调用.