iT邦幫忙

2024 iThome 鐵人賽

DAY 15
0

開始測試前,讓我們在 defineExpose 追加資料,方便進行測試。

src\components\util-party-popper\util-party-popper.vue

...

<script setup lang="ts">
...

// #region Methods
defineExpose({
  emit,
  groupIndex,
  particleSystem,
});
// #endregion Methods
</script>

現在讓我們新增測試檔案。

src\components\util-party-popper\util-party-popper.spec.ts

import { mount } from '@vue/test-utils';
import { test, expect } from 'vitest';

import UtilPartyPopper from './util-party-popper.vue';

test('測試案例', () => {
  const wrapper = mount(UtilPartyPopper);
  expect(wrapper).toBeDefined();
})

新增測試案例

讓我們依序新增各種測試案例吧。∠( ᐛ 」∠)_

元件主體

src\components\util-party-popper\util-party-popper.spec.ts

import { mount } from '@vue/test-utils';
import { test, expect } from 'vitest';

import UtilPartyPopper from './util-party-popper.vue';

test('必須包含一個 canvas', () => {
  const wrapper = mount(UtilPartyPopper);
  expect(wrapper).toBeDefined();

  const canvas = wrapper.find('canvas');
  expect(canvas).toBeDefined();
})

執行測試之後會發現失敗了。( ・ิω・ิ)

FAIL  src/components/util-party-popper/util-party-popper.spec.ts > 必須包含一個 canvas
TypeError: this._gl.getContextAttributes is not a function
 ❯ new ThinEngine dev/core/src/Engines/thinEngine.ts:409:41
 ❯ new Engine dev/core/src/Engines/engine.ts:344:9
 ❯ src/components/util-party-popper/util-party-popper.vue:231:18
    229|   if (!canvas) return;
    230| 
    231|   engine.value = new Engine(canvas, true, {
       |                  ^
    232|     alpha: true,
    233|   });

這是因為我們的測試執行環境中不支援 canvas,讓我們加入 canvas 支援吧。

不過目前以下方法皆失敗:

不是測試卡住就是發生 WebGL not supported。(›´ω`‹ )

只好放棄此元件的單元測試了。( ´•̥̥̥ ω •̥̥̥` )

讓我們先暫時將此測試標記為 skip,跳過此測試。

src\components\util-party-popper\util-party-popper.spec.ts

...

test.skip('必須包含一個 canvas', () => {
  ...
})

希望未來有一天找到解決方法。(´・ω・`)

總結

  • 單元測試的模擬環境不支援 canvas
  • 目前暫時找不到方法

以上程式碼已同步至 GitLab,大家可以前往下載:

GitLab - D15


上一篇
D14 - 拉炮:開發元件
下一篇
D16 - 拉炮:更多範例
系列文
要不要 Vue 點酷酷的元件?19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言