我有一个复选框组件,由于Safari的错误,我更改了
@input=input() to @change='input'
因为Safari没有输入事件。
<template>
<div
class="checkbox">
<input
....
@change="input">
</div>
</template>
<script>
export default {
....
methods: {
input () {
/**
* Input event on change
*
* @event input
* @type {Boolean}
*/
this.$emit('input', this.$refs.checkbox.checked)
}
}
}
</script>
describe('...', () => {
beforeEach(async () => {
const input = wrapper.find('input')
jest.spyOn(wrapper.vm, 'input')
input.trigger('change') // told this is incorrect
jest.runAllTimers()
})
it('[positive] should emit an input event with the input\'s value', () => {
expect(wrapper.emitted().input).toBeTruthy()
expect(wrapper.emitted().input).toHaveLength(1)
expect(wrapper.emitted().input[0]).toEqual([false])
})
it('[positive] should call the input() method with the target value', () => {
// this is wrong also, because the expectation will always be true
wrapper.vm.input()
expect(wrapper.vm.input).toHaveBeenCalled()
})
})
如何正确设置第二项测试?为什么在单元测试中input.trigger('change')是错误的?
答案 0 :(得分:1)
我的第二项测试设置为始终为真。我叫这个函数
wrapper.vm.input()
,然后断言它将被调用,这肯定是正确的,所以这是一个不好的测试。
input.trigger('change')
...是正确的,那正是我所拥有的。这是我的重构测试:
describe('when the checkbox state is changed', () => {
let input
beforeEach(() => {
input = wrapper.find('input')
jest.spyOn(wrapper.vm, 'input')
jest.runAllTimers()
})
it('[positive] should emit an input event with the input\'s value', () => {
input.trigger('change')
expect(wrapper.emitted().input).toBeTruthy()
expect(wrapper.emitted().input).toHaveLength(1)
expect(wrapper.emitted().input[0]).toEqual([false])
})
it('[negative] should not emit an input event with the input\'s value', () => {
input.trigger('input')
expect(wrapper.emitted().input).toBeFalsy()
})
})