Vitest配置問題紀錄

yurukuma
1 min readFeb 28, 2023

--

如何在vitest中使用browser API

error訊息

  • ReferenceError: document is not defined

原因

預設環境是node,如果需要使用browser API(例如location物件),需要在執行vitest指令時帶上–environment參數,例如:

"test": "vitest --environment jsdom"

注意,使用jsdom或happy-dom環境需要額外安裝相應的dependency。

  • window.matchMedia is not a function
// setup.js
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
})
// vite.config.js
test: {
include: ['test/**/*.test.ts'],
environment: 'jsdom',
deps: {
inline: ['@vue', '@vueuse', 'vue-demi', '@vue/composition-api'],
},
setupFiles: [resolve(__dirname, 'test/setup/setup.ts')],
reporters: 'dot',
},

參考[1]

在vitest mock $t跟 t

// setup.js
import { mount, config } from "@vue/test-utils"
import { useI18n } from "vue-i18n"

vi.mock("vue-i18n")

// 當在測試程式中呼叫 useI18n() 這個 hook 時(vue 3 setup script會用到這個hook),
// 會回傳一個包含 t 屬性的物件,
// 而 t 屬性的回傳值則會是傳入的 tKey
// 為了在測試程式中方便地模擬 t 函式的行為
useI18n.mockReturnValue({
t: (tKey) => tKey,
})
// 模擬全域的 $t 變數。當在 Vue 組件中呼叫 $t 時,
// 會回傳傳入的參數。這樣做是為了在測試程式中方便地模擬 Vue 組件中的 $t 行為
config.global.mocks = {
$t: (tKey) => tKey,
}

Reference

[1]https://vitest.dev/guide/environment.html#test-environment

[2]https://github.com/vitest-dev/vitest/issues/821

[3]https://stackoverflow.com/questions/72260793/best-way-to-mock-stub-vue-i18n-translations-in-a-vue3-component-when-using-vites

--

--

yurukuma
yurukuma

Written by yurukuma

I’m a front-end developer. Let’s learning by doing:)

No responses yet