以下是我的组件中的代码和我当前的测试:
// component script
import { mapActions } from 'vuex'
export default {
name: 'foo',
mounted () {
this.firstMethod()
.then(() => {
this.secondMethod()
})
.then(() => {
this.thirdMethod()
})
},
methods: {
...mapActions([
'firstMethod',
'secondMethod',
'thirdMethod'
])
}
}
// test
import { shallow, createLocalVue } from 'vue-test-utils'
import Vuex from 'vuex'
import Foo from '../Foo.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Foo.vue', () => {
let actions
let store
let wrapper
beforeEach(() => {
actions = {
firstMethod: sinon.stub().resolves(),
secondMethod: sinon.stub().resolves(),
thirdMethod: sinon.stub(),
}
store = new Vuex.Store({
actions
})
wrapper = shallow(Foo, { store, localVue })
})
it.only('calls store actions when mounted', () => {
expect(actions.firstMethod.called).toBe(true) // succeedes
expect(actions.secondMethod.called).toBe(true) // fails
expect(actions.thirdMethod.called).toBe(true) // fails
})
})
我希望所有三个expects
都能成功,因为我了解.resolves()
方法会使stub
返回已解决的承诺,而这又会触发下一个调用组件上的then
方法。但事实并非如此。
我应该如何测试确实调用了Vuex操作?
如果有意义的话,我愿意接受多次测试,而不仅仅是一次测试。或者甚至将3次调用重构为其他内容,只要在成功时按顺序调用它们。
谢谢!
答案 0 :(得分:0)
好的,所以我改变了组件挂载方法的结构,但测试也适用于原始代码。
以下是测试的更新组件。
// component script
import { mapActions } from 'vuex'
export default {
name: 'foo',
mounted () {
this.mount()
},
methods: {
async mount () {
await this.firstMethod()
await this.secondMethod()
await this.thirdMethod()
},
...mapActions([
'firstMethod',
'secondMethod',
'thirdMethod'
])
}
}
// test
import { shallow, createLocalVue } from 'vue-test-utils'
import Vuex from 'vuex'
import Foo from '../Foo.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Foo.vue', () => {
let actions
let store
let wrapper
beforeEach(() => {
actions = {
firstMethod: sinon.stub().resolves(),
secondMethod: sinon.stub().resolves(),
thirdMethod: sinon.stub().resolves()
}
store = new Vuex.Store({
actions
})
wrapper = shallow(Foo, { store, localVue })
})
it('calls store actions when mounted', async () => {
await expect(actions.firstMethod.called).toBe(true)
await expect(actions.secondMethod.called).toBe(true)
await expect(actions.thirdMethod.called).toBe(true)
})
})
我希望这有助于某人!