我正在尝试测试一个组件(Mocha/Chai/Sinon 框架),但我收到一个断言错误,我找不到它引发此错误的原因。我想在 'input.dispatchEvent(enterEvent)' 被触发后我错过了一些东西。 ..
1) should change the title
ChangeTitleComponent.vue changeTitle
AssertionError: expected commit to have been called with arguments changeTitle, { id: "1", title: "My New Title" }
at Context.<anonymous> (webpack:///test/unit/specs/components/ChangeTitleComponent.spec.js:40:40 <- index.js:17914:51
ChangeTitleComponent.spec.js
import Vue from 'vue'
import ChangeTitleComponent from '@/components/ChangeTitleComponent'
import store from '@/vuex/store'
describe('ChangeTitleComponent.vue', () => {
describe('changeTitle', () => {
var component
beforeEach(() => {
var vm = new Vue({
template: '<change-title-component :title="title" :id="id" ref="changetitlecomponent">' +
'</change-title-component></div>',
components: {
ChangeTitleComponent
},
props: ['title', 'id'],
store
}).$mount()
component = vm.$refs.changetitlecomponent
})
it('should change the title', () => {
// stub $emit method
sinon.stub(store, 'commit')
// stub store's dispatch method
sinon.stub(store, 'dispatch')
// check component label text
expect(component.$el.textContent).to.equal('Change the title of your shopping list here ')
let newTitle = 'My New Title'
// simulate input Enter event
const input = component.$el.querySelector('input')
input.value = newTitle
const enterEvent = new window.Event('keypress', { which: 13 })
input.dispatchEvent(enterEvent)
component._watcher.run()
// TESTING ACTION: store.commit(types.CHANGE_TITLE, data)
expect(store.commit).to.have.been.calledWith('changeTitle', {title: newTitle, id: '1'})
// TESTING ACTION: store.dispatch('updateList', data.id)
expect(store.dispatch).to.have.been.calledWith('updateList', '1')
store.dispatch.restore()
component.commit.restore()
})
})
})
更改标题组件.vue
<template>
<div>
<em>Change the title of your shopping list here</em>
<input :value="title" @input="onInput({ title: $event.target.value, id: id })"/>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
props: ['title', 'id'],
methods: mapActions({ // dispatching actions in components
onInput: 'changeTitle'
})
}
</script>
vuex/actions.js
import * as types from './mutation_types'
import api from '../api'
import getters from './getters'
export default {
changeTitle: (store, data) => {
store.commit(types.CHANGE_TITLE, data)
store.dispatch('updateList', data.id)
},
updateList: (store, id) => {
let shoppingList = getters.getListById(store.state, id)
return api.updateShoppingList(shoppingList)
.then(response => {
return response
})
.catch(error => {
throw error
})
}
}
vuex/mutations.js
import * as types from './mutation_types'
import getters from './getters'
import _ from 'underscore'
export default {
[types.CHANGE_TITLE] (state, data) {
getters.getListById(state, data.id).title = data.title
}
}
vuex/mutation_types.js
export const CHANGE_TITLE = 'CHANGE_TITLE'