In this article, we will analyze ErrorBoundary class component in Zustand’s test case. Error handling is a crucial part of any React application.
Overview of the Test Case
Here’s the test case we’ll be exploring:
// Picked from https://github.com/pmndrs/zustand/blob/v4.5.5/tests/basic.test.tsx#L378 it('can throw an error in equality checker', async () => { console.error = vi.fn() type State = { value: string | number } const initialState: State = { value: 'foo' } const useBoundStore = createWithEqualityFn(() => initialState, Object.is) const { setState } = useBoundStore const selector = (s: State) => s const equalityFn = (a: State, b: State) => // @ts-expect-error This function is supposed to throw an error a.value.trim() === b.value.trim() class ErrorBoundary extends ClassComponent { constructor(props: { children?: ReactNode | undefined }) { super(props) this.state = { hasError: false } } static getDerivedStateFromError() { return { hasError: true } } render() { return this.state.hasError ? <div>errored</div> : this.props.children } } function Component() { useBoundStore(selector, equalityFn) return <div>no error</div> } const { findByText } = render( <strictmode> <errorboundary> <component></component> </errorboundary> </strictmode>, ) await findByText('no error') act(() => { setState({ value: 123 }) }) await findByText('errored') })
This test verifies that when an error occurs inside an equality checker, the error is caught and handled gracefully by an ErrorBoundary component.
Key Concepts in the Test Case
1. Zustand’s createWithEqualityFn
Zustand allows you to define stores with custom equality functions using createWithEqualityFn. In this test, the initial state is defined as:
const initialState: State = { value: 'foo' }
The createWithEqualityFn function is used to create a store where the equality function is defined to compare states based on whether the value property is equal. In this case, the equality checker is intentionally set to throw an error when value is of a type other than string:
You can intentionally throw errors in your test cases to ensure your code handles errors as expected.
const equalityFn = (a: State, b: State) => a.value.trim() === b.value.trim() // Throws error if 'value' is not a string
The test case expects this equality function to fail when value becomes a number, causing the error handler to come into play.
2. Custom ErrorBoundary Component
React’s ErrorBoundary component is a common pattern used to catch JavaScript errors in a component tree, and Zustand has taken this approach to test how errors within their state management are handled. This particular test case defines a custom ErrorBoundary component directly inside the test. I mean, how often do you come across a test case that has the custom ErrorBoundary with in a “test case”?
class ErrorBoundary extends ClassComponent { constructor(props: { children?: ReactNode | undefined }) { super(props) this.state = { hasError: false } } static getDerivedStateFromError() { return { hasError: true } } render() { return this.state.hasError ? <div>errored</div> : this.props.children } }
How it works:
The component uses the lifecycle method getDerivedStateFromError() to catch errors and update its state (hasError) to true.
-
If an error is detected, the component renders
errored. Otherwise, it renders its children.
In typical production use, ErrorBoundary components are created as reusable elements to catch and display errors across the application. However, embedding the ErrorBoundary directly inside a test case like this provides fine-grained control over error testing, allowing you to assert that the component reacts correctly when errors occur in specific parts of the application.
3. Testing Error Handling with Vitest
In this test case, Vitest is used as the testing framework. Here’s how it works with Zustand:
- Rendering the Component: The Component that uses the useBoundStore hook is rendered inside the ErrorBoundary within a React StrictMode block. This ensures that errors inside the equality checker can be caught.
const { findByText } = render( <strictmode> <errorboundary> <component></component> </errorboundary> </strictmode>, ) await findByText('no error')
At this point, the test verifies that no error has been thrown yet and checks for the text no error.
Triggering the Error: After the component is initially rendered without errors, the test triggers an error by updating the store’s state to a number:
act(() => { setState({ value: 123 }) })
This causes the equality function to throw an error, as value.trim() is no longer valid for a number type.
Asserting the Error Handling: Once the error is thrown, the ErrorBoundary catches it, and the test waits for the UI to render the errored message:
await findByText('errored')
- This assertion confirms that the error was properly caught and displayed by the ErrorBoundary
Why This Approach is Unique
What makes this test case particularly interesting is the use of an inline ErrorBoundary component within a unit test. Typically, error boundaries are part of the main React app, wrapping components in the main render tree. However, Zustand's approach to create an error boundary in the test suite itself offers a more flexible and isolated way to test how errors are handled under specific conditions.
By directly controlling the boundary within the test, Zustand ensures:
Granularity: The test can focus on how errors in a particular part of the application (like the equality checker) are handled, without needing to rely on global error boundaries.
Test Isolation: The ErrorBoundary exists only within the scope of this test, reducing potential side effects or dependencies on the app’s broader error-handling logic.
About us:
At Think Throo, we are on a mission to teach the advanced codebase architectural concepts used in open-source projects.
10x your coding skills by practising advanced architectural concepts in Next.js/React, learn the best practices and build production-grade projects.
We are open source — https://github.com/thinkthroo/thinkthroo (Do give us a star!)
Up skill your team with our advanced courses based on codebase architecture. Reach out to us at hello@thinkthroo.com to learn more!
References:
- https://github.com/pmndrs/zustand/blob/v4.5.5/tests/basic.test.tsx#L378
Atas ialah kandungan terperinci Begini cara kes ujian Zustand menggunakan ErrorBoundary.. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Aplikasi JavaScript di dunia nyata termasuk pembangunan depan dan back-end. 1) Memaparkan aplikasi front-end dengan membina aplikasi senarai TODO, yang melibatkan operasi DOM dan pemprosesan acara. 2) Membina Restfulapi melalui Node.js dan menyatakan untuk menunjukkan aplikasi back-end.

Penggunaan utama JavaScript dalam pembangunan web termasuk interaksi klien, pengesahan bentuk dan komunikasi tak segerak. 1) kemas kini kandungan dinamik dan interaksi pengguna melalui operasi DOM; 2) pengesahan pelanggan dijalankan sebelum pengguna mengemukakan data untuk meningkatkan pengalaman pengguna; 3) Komunikasi yang tidak bersesuaian dengan pelayan dicapai melalui teknologi Ajax.

Memahami bagaimana enjin JavaScript berfungsi secara dalaman adalah penting kepada pemaju kerana ia membantu menulis kod yang lebih cekap dan memahami kesesakan prestasi dan strategi pengoptimuman. 1) aliran kerja enjin termasuk tiga peringkat: parsing, penyusun dan pelaksanaan; 2) Semasa proses pelaksanaan, enjin akan melakukan pengoptimuman dinamik, seperti cache dalam talian dan kelas tersembunyi; 3) Amalan terbaik termasuk mengelakkan pembolehubah global, mengoptimumkan gelung, menggunakan const dan membiarkan, dan mengelakkan penggunaan penutupan yang berlebihan.

Python lebih sesuai untuk pemula, dengan lengkung pembelajaran yang lancar dan sintaks ringkas; JavaScript sesuai untuk pembangunan front-end, dengan lengkung pembelajaran yang curam dan sintaks yang fleksibel. 1. Sintaks Python adalah intuitif dan sesuai untuk sains data dan pembangunan back-end. 2. JavaScript adalah fleksibel dan digunakan secara meluas dalam pengaturcaraan depan dan pelayan.

Python dan JavaScript mempunyai kelebihan dan kekurangan mereka sendiri dari segi komuniti, perpustakaan dan sumber. 1) Komuniti Python mesra dan sesuai untuk pemula, tetapi sumber pembangunan depan tidak kaya dengan JavaScript. 2) Python berkuasa dalam bidang sains data dan perpustakaan pembelajaran mesin, sementara JavaScript lebih baik dalam perpustakaan pembangunan dan kerangka pembangunan depan. 3) Kedua -duanya mempunyai sumber pembelajaran yang kaya, tetapi Python sesuai untuk memulakan dengan dokumen rasmi, sementara JavaScript lebih baik dengan MDNWebDocs. Pilihan harus berdasarkan keperluan projek dan kepentingan peribadi.

Peralihan dari C/C ke JavaScript memerlukan menyesuaikan diri dengan menaip dinamik, pengumpulan sampah dan pengaturcaraan asynchronous. 1) C/C adalah bahasa yang ditaip secara statik yang memerlukan pengurusan memori manual, manakala JavaScript ditaip secara dinamik dan pengumpulan sampah diproses secara automatik. 2) C/C perlu dikumpulkan ke dalam kod mesin, manakala JavaScript adalah bahasa yang ditafsirkan. 3) JavaScript memperkenalkan konsep seperti penutupan, rantaian prototaip dan janji, yang meningkatkan keupayaan pengaturcaraan fleksibiliti dan asynchronous.

Enjin JavaScript yang berbeza mempunyai kesan yang berbeza apabila menguraikan dan melaksanakan kod JavaScript, kerana prinsip pelaksanaan dan strategi pengoptimuman setiap enjin berbeza. 1. Analisis leksikal: Menukar kod sumber ke dalam unit leksikal. 2. Analisis Tatabahasa: Menjana pokok sintaks abstrak. 3. Pengoptimuman dan Penyusunan: Menjana kod mesin melalui pengkompil JIT. 4. Jalankan: Jalankan kod mesin. Enjin V8 mengoptimumkan melalui kompilasi segera dan kelas tersembunyi, Spidermonkey menggunakan sistem kesimpulan jenis, menghasilkan prestasi prestasi yang berbeza pada kod yang sama.

Aplikasi JavaScript di dunia nyata termasuk pengaturcaraan sisi pelayan, pembangunan aplikasi mudah alih dan Internet of Things Control: 1. Pengaturcaraan sisi pelayan direalisasikan melalui node.js, sesuai untuk pemprosesan permintaan serentak yang tinggi. 2. Pembangunan aplikasi mudah alih dijalankan melalui reaktnatif dan menyokong penggunaan silang platform. 3. Digunakan untuk kawalan peranti IoT melalui Perpustakaan Johnny-Five, sesuai untuk interaksi perkakasan.


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

MantisBT
Mantis ialah alat pengesan kecacatan berasaskan web yang mudah digunakan yang direka untuk membantu dalam pengesanan kecacatan produk. Ia memerlukan PHP, MySQL dan pelayan web. Lihat perkhidmatan demo dan pengehosan kami.

SublimeText3 Linux versi baharu
SublimeText3 Linux versi terkini

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Muat turun versi mac editor Atom
Editor sumber terbuka yang paling popular

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)