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
以上がZustand のテストケースで ErrorBoundary がどのように使用されるかは次のとおりです。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Web開発におけるJavaScriptの主な用途には、クライアントの相互作用、フォーム検証、非同期通信が含まれます。 1)DOM操作による動的なコンテンツの更新とユーザーインタラクション。 2)ユーザーエクスペリエンスを改善するためにデータを提出する前に、クライアントの検証が実行されます。 3)サーバーとのリフレッシュレス通信は、AJAXテクノロジーを通じて達成されます。

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

ドリームウィーバー CS6
ビジュアル Web 開発ツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、
