Skip to content
70 changes: 70 additions & 0 deletions tests/ssr.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'

interface BearStoreState {
bears: number
}

interface BearStoreAction {
increasePopulation: () => void
}

const initialState = { bears: 0 }
const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
...initialState,
increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
}))

function Counter() {
const { bears, increasePopulation } = useBearStore(
({ bears, increasePopulation }) => ({
bears,
increasePopulation,
})
)

useEffect(() => {
increasePopulation()
}, [increasePopulation])

return <div>bears: {bears}</div>
}

describe.skipIf(!React.version.startsWith('18'))(
Copy link
Member

Choose a reason for hiding this comment

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

Oh, I didn't know about skipIf!

We should use it in jotai too:
https://github.com/pmndrs/jotai/blob/d6afb777705eb3a90385817fd6db30db101f6caa/tests/react/transition.test.tsx#L12C1-L16

Free free to open a PR there.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am also glad to have learned about skipIf, and I will apply refactoring accordingly in Jotai as well

Copy link
Collaborator

Choose a reason for hiding this comment

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

I guess we are good to merge the changes :D. BTW, good job.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you so much for your review.
I'm delighted to learn about the useful functions of vitest. I'll continue to check if there are any opportunities for further contributions.

'ssr behavior with react 18',
() => {
it('should handle different states between server and client correctly', async () => {
const { hydrateRoot } = await vi.importActual<
typeof import('react-dom/client')
>('react-dom/client')

const markup = renderToString(
<React.Suspense fallback={<div>Loading...</div>}>
<Counter />
</React.Suspense>
)

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

expect(container.textContent).toContain('bears: 0')

await act(async () => {
hydrateRoot(
container,
<React.Suspense fallback={<div>Loading...</div>}>
<Counter />
</React.Suspense>
)
})

const bearCountText = await screen.findByText('bears: 1')
expect(bearCountText).not.toBeNull()
document.body.removeChild(container)
})
}
)