详解Jest结合Vue-test-utils使用的初步实践

2020-06-14 06:26:38易采站长站整理


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()
});

但是在执行之后我们发现并非如此,spy并未被调用,原因是:

watch中的方法被Vue**推迟**到了更新的下一个循环队列中去异步执行,如果这个watch被触发多次,只会被推送到队列一次。这种缓冲行为可以有效的去掉重复数据造成的不必要的性能开销。

所以当我们设置了inputValue为’ok’之后,watch中的方法并没有立刻执行,但是expect却执行了,所以断言失败了。

解决方法就是将断言放到$nextTick中,在下一个循环队列中执行,同时在expect后面执行Jest提供的done()方法,Jest会等到done()方法被执行才会结束测试。


it('is called with the new value in other cases', (done) = > {
wrapper.vm.inputValue = 'ok';