Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions tests/ssr.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { StrictMode } from 'react'
import { act } from '@testing-library/react'
import { hydrateRoot } from 'react-dom/client'
import { renderToString } from 'react-dom/server'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { proxy, useSnapshot } from 'valtio'

describe('ssr', () => {
afterEach(() => {
document.body.innerHTML = ''
})

it('should return initial snapshot in SSR', () => {
const obj = proxy({ count: 0 })

const Counter = () => {
const snap = useSnapshot(obj)
return <div>count: {snap.count}</div>
}

const view = renderToString(
<StrictMode>
<Counter />
</StrictMode>,
)

expect(view).toContain('count:')
expect(view).toContain('0')
})

it('should return the latest snapshot after proxy state changes', () => {
const obj = proxy({ count: 0 })

obj.count = 5

const Counter = () => {
const snap = useSnapshot(obj)
return <div>count: {snap.count}</div>
}

const view = renderToString(
<StrictMode>
<Counter />
</StrictMode>,
)

expect(view).toContain('count:')
expect(view).toContain('5')
})

it('should not cause hydration mismatch', async () => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is too naive. The AI doesn't understand the underlying problem.
Try to create a bug so that such a hydration-mismatch test fails.
I'm not sure if it's possible. But, otherwise, it's not valid for getServerSnapshot test.

const obj = proxy({ count: 0 })

const Counter = () => {
const snap = useSnapshot(obj)
return <div>count: {snap.count}</div>
}

const view = renderToString(
<StrictMode>
<Counter />
</StrictMode>,
)

const container = document.createElement('div')
container.innerHTML = view
document.body.appendChild(container)

const errorSpy = vi.spyOn(console, 'error')

await act(() =>
hydrateRoot(
container,
<StrictMode>
<Counter />
</StrictMode>,
),
)

expect(errorSpy).not.toHaveBeenCalled()

errorSpy.mockRestore()
})
})
Loading