Skip to content

Commit ed30dc1

Browse files
authored
test: add onMount test and replace onDestory test (#303)
1 parent c568b5d commit ed30dc1

File tree

5 files changed

+55
-77
lines changed

5 files changed

+55
-77
lines changed

src/__tests__/fixtures/Mounter.svelte

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<script>
2+
import { onDestroy,onMount } from 'svelte'
3+
4+
export let onMounted
5+
export let onDestroyed
6+
7+
onMount(() => onMounted())
8+
onDestroy(() => onDestroyed())
9+
</script>
10+
11+
<button />

src/__tests__/fixtures/Stopwatch.svelte

-40
This file was deleted.

src/__tests__/mount.test.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { describe, expect, test, vi } from 'vitest'
2+
3+
import { act, render, screen } from '..'
4+
import Mounter from './fixtures/Mounter.svelte'
5+
6+
describe('mount and destroy', () => {
7+
const handleMount = vi.fn()
8+
const handleDestroy = vi.fn()
9+
10+
test('component is mounted', async () => {
11+
await act(() => {
12+
render(Mounter, { onMounted: handleMount, onDestroyed: handleDestroy })
13+
})
14+
15+
const content = screen.getByRole('button')
16+
17+
expect(handleMount).toHaveBeenCalledOnce()
18+
expect(content).toBeInTheDocument()
19+
})
20+
21+
test('component is destroyed', async () => {
22+
const { unmount } = render(Mounter, {
23+
onMounted: handleMount,
24+
onDestroyed: handleDestroy,
25+
})
26+
27+
await act(() => unmount())
28+
const content = screen.queryByRole('button')
29+
30+
expect(handleDestroy).toHaveBeenCalledOnce()
31+
expect(content).not.toBeInTheDocument()
32+
})
33+
})

src/__tests__/unmount.test.js

-35
This file was deleted.

vite.config.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,23 @@ import { svelte } from '@sveltejs/vite-plugin-svelte'
22
import { defineConfig } from 'vite'
33

44
// https://vitejs.dev/config/
5-
export default defineConfig({
5+
export default defineConfig(({ mode }) => ({
66
plugins: [svelte()],
7+
resolve: {
8+
// Ensure `browser` exports are used in tests
9+
// Vitest prefers modules' `node` export by default
10+
// Svelte's `node` export is its SSR bundle, which does not have onMount
11+
// https://github.com/testing-library/svelte-testing-library/issues/222#issuecomment-1909993331
12+
conditions: mode === 'test' ? ['browser'] : [],
13+
},
714
test: {
815
environment: 'jsdom',
916
setupFiles: ['./src/__tests__/_vitest-setup.js'],
17+
mockReset: true,
18+
unstubGlobals: true,
1019
coverage: {
1120
provider: 'v8',
1221
include: ['src'],
1322
},
1423
},
15-
})
24+
}))

0 commit comments

Comments
 (0)