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< { children?: ReactNode | undefined }, { hasError: boolean } > { 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 /> </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< { children?: ReactNode | undefined }, { hasError: boolean } > { 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 /> </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
以上是Here’s how Zustand’s test-case uses ErrorBoundary.的详细内容。更多信息请关注PHP中文网其他相关文章!

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

Atom编辑器mac版下载
最流行的的开源编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版
中文版,非常好用

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)