跳至主要內容

常見問題


這個函式庫也適用於 SvelteKit 嗎?

是的,它適用。它需要與「一般」Svelte 專案相同的設定

為什麼渲染元件時沒有呼叫 onMount

由於測試是在 Node 環境而不是瀏覽器環境中執行,因此它使用 Svelte 的 SSR 導出,將所有生命週期事件宣告為無操作。

一個解決方案是將 Vite 設定為在測試中使用瀏覽器解析。

vite.config.js
import {svelte} from '@sveltejs/vite-plugin-svelte'
import {defineConfig} from 'vite'

export default defineConfig(({mode}) => ({
plugins: [svelte()],
resolve: {
// The default would be [ 'svelte', 'node' ]
// as set by vite-plugin-svelte and vitest.
// This sets [ 'browser', 'svelte', 'node' ]
conditions: mode === 'test' ? ['browser'] : [],
},
test: {
environment: 'jsdom',
},
}))

請參閱 svelte-testing-library 的 issue 222 以了解更多詳細資訊。

我該如何測試檔案上傳?

請使用 @testing-library/user-event 中的 upload 工具,而不是 fireEvent。它在 jsdomhappy-dom 中都能正常運作。

test('upload file', async () => {
const user = userEvent.setup()

render(Uploader)
const file = new File(['hello'], 'hello.png', {type: 'image/png'})
const input = screen.getByLabelText(/upload file/i)

await user.upload(input, file)

expect(input.files[0]).toBe(file)
expect(input.files.item(0)).toBe(file)
expect(input.files).toHaveLength(1)
})

為什麼 轉場事件 沒有執行?

jsdomrequestAnimationFrame 實作在 Vitest 中可能不太可靠。為了解決這個問題,您可以

  • 切換到 happy-dom,如果可以的話,它沒有相同的問題
  • 替換 requestAnimationFrame 的實作
beforeEach(() => {
const raf = fn => setTimeout(() => fn(new Date()), 16)
vi.stubGlobal('requestAnimationFrame', raf)
})

// Alternatively, set `unstubGlobals: true` in vitest.config.js
afterEach(() => {
vi.unstubAllGlobals()
})

請參閱 svelte-testing-library 的 issue 206 以了解更多詳細資訊。