详解Jest结合Vue-test-utils使用的初步实践(6)
测试计算属性
创建Test2组件,实现功能是使用计算属性将输入框输入的字符翻转:
<template>
<div class="wrapper">
<label for="input">输入:</label>
<input id="input" type="text" v-model="inputValue">
<p>输出:{{outputValue}}</p>
</div>
</template>
<script>
export default {
name: 'Test2',
props: {
needReverse: {
type: Boolean,
default: false
}
},
data() {
return {
inputValue: ''
}
},
computed: {
outputValue () {
return this.needReverse ? ([...this.inputValue]).reverse().join('') : this.inputValue
}
},
methods: {},
components: {}
}
</script>
<style scoped>
.wrapper {
width: 300px;
margin: 0 auto;
text-align: left;
}
</style>
在Test2.spec.js中,可以通过wrapper.vm属性访问一个实例所有的方法和属性。这只存在于 Vue 组件包裹器中。
describe('Test for Test2 Component', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(Test2);
});
afterEach(() => {
wrapper.destroy()
});
it('returns the string in normal order if reversed property is not true', () => {
wrapper.setProps({needReverse: false});
wrapper.vm.inputValue = 'ok';
expect(wrapper.vm.outputValue).toBe('ok')
});
it('returns the string in normal order if reversed property is not provided', () => {
wrapper.vm.inputValue = 'ok';
expect(wrapper.vm.outputValue).toBe('ok')
});
it('returns the string in reversed order if reversed property is true', () => {
wrapper.setProps({needReverse: true});
wrapper.vm.inputValue = 'ok';
expect(wrapper.vm.outputValue).toBe('ko')
})
});
测试监听器
Vue提供的watch选项提供了一个更通用的方法,来响应数据的变化。
为Test添加侦听器:
watch: {
inputValue: function(newValue, oldValue) {
if (newValue.trim().length > 0 && newValue !== oldValue) {
this.printNewValue(newValue)
}
}
},
methods: {
printNewValue(value) {
console.log(value)
}
},
为了测试,首先开始测试前将console的log方法用jest的spyOn方法mock掉,最好在测试结束后通过mockClear方法将其重置,避免无关状态的引入。
describe('Test watch', () = > {
let spy;
beforeEach(() = > {
wrapper = shallow(Test2);
spy = jest.spyOn(console, 'log')
});
afterEach(() = > {
wrapper.destroy();
spy.mockClear()
});
}
然后执行给inputValue赋值,按照预期,spy方法会被调用
it('is called with the new value in other cases', () = > {
wrapper.vm.inputValue = 'ok';
expect(spy).toBeCalled()
});
内容版权声明:除非注明,否则皆为本站原创文章。
