我有一个Vue组件modal
,其父级传递onClose
道具。点击ok
按钮后,系统会触发onClose
方法。代码如下:
Vue.component('modal', {
template: '#modal-template',
props: {
onClose: {
type: Function
}
},
methods: {
ok() {
this.onClose();
}
}
})
// start app
new Vue({
el: '#app',
methods: {
close() {
alert('close')
}
}
})

<script src="https://npmcdn.com/vue@1.0.26/dist/vue.min.js"></script>
<script type="x/template" id="modal-template">
<div class="modal-mask">
<button @click='ok()'> OK </button>
</div>
</script>
<div id="app">
<modal :on-close="close" ></modal>
</div>
&#13;
我认为modal
组件的单元测试应该在spy
方法上定义close
,因此测试应如下所示:
let vm = new Vue({
template: '<div><modal v-ref:test-component :on-close="close"></modal></div>',
methods: {
close: sinon.spy()
},
components: { ConfirmModal }
}).$mount()
const modal = vm.$refs.testComponent
modal.ok()
expect(vm.close).have.been.called()
测试失败,错误: TypeError: [Function] is not a spy or a call to a spy!
答案 0 :(得分:0)
以下是单元测试的摘录:
it('methods', function () {
var spy = jasmine.createSpy()
var vm = new Vue({
el: el,
template: '<a v-on:click="test"></a>',
data: {a: 1},
methods: {
test: spy
}
})
var a = el.firstChild
trigger(a, 'click')
expect(spy.calls.count()).toBe(1)
vm.$destroy()
trigger(a, 'click')
expect(spy.calls.count()).toBe(1)
})