概述
最近玩 Jest,測試 Vue 組件上的事件,有一些心得,記錄下來供以后開發時參考,相信對其他人也有用。
事件測試
對於 Vue 組件上的事件,分為 2 種,一種是子組件 Emit 的事件,另一種是插件的事件回調。
子組件 emit 的事件
對於子組件 Emit 的事件,我們使用 Jest mock 這個子組件,然后使用 Vue-Test-Util 提供的方法,模擬 emit 事件即可,示例如下:
// ChildComponent
export default {
name: 'ChildComponent',
};
// ParentComponent
<template>
<div>
<child-component @custom="onCustom" />
<p v-if="emitted">Emitted!</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent';
export default {
name: 'ParentComponent',
components: { ChildComponent },
data() {
return {
emitted: false,
};
},
methods: {
onCustom() {
this.emitted = true;
},
},
};
</script>
// test.js
import { shallowMount } from '@vue/test-utils';
import ChildComponent from './helper/ChildComponent';
import ParentComponent from './helper/ParentComponent.vue';
describe('emit custom event', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it("displays 'Emitted!' when custom event is emitted", () => {
const wrapper = shallowMount(ParentComponent);
wrapper.find(ChildComponent).vm.$emit('custom');
expect(wrapper.vm.emitted).toBeTruthy();
expect(wrapper.html()).toContain('Emitted!');
});
});
插件的事件回調
有些插件會提供事件回調,比如 sortable.js 就提供這樣的事件回調:
var sortable = new Sortable(el, {
group: "name",
sort: true,
onSort: function (/**Event*/evt) {
// 事件回調
},
});
這個時候我們只需要用 Jest mock 這個插件,然后直接手動執行這個事件綁定的回調函數即可。因為 Jest 代理了這個插件,所以實際上這個插件並沒有真正被引入,所以所有這個插件執行的操作都需要我們手動調用或者模擬執行。實例如下:
// module.js
function ChildModule(options) {}
export default ChildModule;
// ParentComponent
<template>
<div>
<child-component @custom="onCustom" />
<p v-if="called">Called!</p>
</div>
</template>
<script>
import ChildModule from './ChildModule';
export default {
name: 'ParentComponent',
data() {
return {
called: false,
};
},
created() {
this.childModule = new ChildModule({
callback: () => {
this.called = true;
},
});
},
};
</script>
// test.js
import { shallowMount } from '@vue/test-utils';
import ChildModule from './helper/ChildModule';
import ParentComponent from './helper/ParentComponent.vue';
jest.mock('./helper/ChildModule');
describe('emit custom event', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it("displays 'Called!' when callback is called", async () => {
const wrapper = shallowMount(ParentComponent);
ChildModule.mock.calls[0][0].callback();
expect(wrapper.vm.called).toBeTruthy;
expect(wrapper.html()).toContain('Called!');
});
});
需要說明的是:我們是通過這段代碼執行回調函數的:
ChildModule.mock.calls[0][0].callback();
