forked from TechBowl-japan/react-stations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstation04.test.tsx
66 lines (51 loc) · 1.47 KB
/
station04.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, waitFor } from '@testing-library/react'
import { fetchMock } from './mock/fetch'
const React: typeof import('react') = await vi.importActual('react')
const useState = vi.fn()
vi.mock('react', () => {
return {
...React,
useState,
}
})
const { App } = (await import('../src/App')) as { App: React.ComponentType<{}> }
describe('Station No.4', () => {
const fetch = vi.fn()
let setState: React.Dispatch<React.SetStateAction<unknown>> | undefined
window.fetch = fetch
fetch.mockImplementation(fetchMock)
beforeEach(() => {
useState.mockImplementation((v?: unknown) => {
const [value, dispatcher] = React.useState(v)
setState = dispatcher
return [value, dispatcher]
})
})
afterEach(() => {
vi.clearAllMocks()
})
it('<App /> calls useState', async () => {
await render(<App />)
await waitFor(() => {
expect(useState).toBeCalled()
})
})
it('<img> uses a state value', async () => {
const res = await render(<App />)
const img = res.container.querySelector('img')
const injectValue = 'http://localhost/doggo'
if (img === null) {
throw new Error('img is null')
}
expect(img.src).toBeTruthy()
expect(useState).toBeCalledWith(img.src)
useState.mockClear()
act(() => {
if (setState) {
setState(injectValue)
}
})
expect(img.src).toBe(injectValue)
})
})