测试 React Server Components

编辑页面

了解如何为 Expo 中的 React Server Components 编写单元测试。

Android
iOS
Web

For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.

重要 本指南涉及仍在开发中的 experimental 功能 React Server Components。

React Server Components(RSC)是 React 中的一项新功能,允许你构建在服务器上渲染并可在客户端进行 hydration 的组件。本指南提供了如何在你的项目中为 RSC 编写单元测试的详细信息。

Jest 测试

React Server Components 运行在 Node.js 上。这意味着 Jest 本身就可以较为接近地模拟服务端渲染环境;相比之下,基于客户端的测试则需要一个 Jest 预设来在 Node.js 和 Web 浏览器之间通信。

设置

虽然标准的服务端渲染仅适用于 Web,但 Expo 的通用 RSC 会为每个平台打包自定义的服务端渲染器。这意味着支持平台特定的文件扩展名。例如,在为 iOS 应用编写 Server Components 时,平台特定扩展名如 *.ios.js*.native.ts 都会被解析。

jest-expo 为测试 Server Components 提供了几种不同的预设:

Runner描述
jest-expo/rsc/android仅适用于 Android 的 RSC runner。使用 *.android.js*.native.js*.js 文件。
jest-expo/rsc/ios仅适用于 iOS 的 RSC runner。使用 *.ios.js*.native.js*.js 文件。
jest-expo/rsc/web仅适用于 Web 的 RSC runner。使用 *.web.js*.js 文件。
jest-expo/rsc一个组合了以上 runner 的多 runner。

要为 RSC 配置 Jest,请在项目根目录下创建一个 jest-rsc.config.js 文件:

jest-rsc.config.js
module.exports = require('jest-expo/rsc/jest-preset');

然后,你可以在 package.json 中添加一个名为 test:rsc 的脚本,例如:

package.json
{ "scripts": { "test:rsc": "jest --config jest-rsc.config.js" } }

编写测试

测试应写在 __rsc_tests__ 目录中,以防止 Jest 在服务端运行你的客户端测试。

__rsc_tests__/my-component.test.ts
/// <reference types="jest-expo/rsc/expect" /> import { LinearGradient } from 'expo-linear-gradient'; it(`renders to RSC`, async () => { const jsx = ( <LinearGradient colors={['cyan', '#ff00ff', 'rgba(0,0,0,0)', 'rgba(0,255,255,0.5)']} testID="gradient" /> ); await expect(jsx).toMatchFlight(`1:I["src/LinearGradient.tsx",[],"LinearGradient"] 0:["$","$L1",null,{"colors":["cyan","#ff00ff","rgba(0,0,0,0)","rgba(0,255,255,0.5)"],"testID":"gradient"},null]`); });

你在测试文件中导入的任何代码都会在服务器环境中运行。你可以导入诸如 react-serverserver-only 这样的仅服务端模块。这对于判断某个库是否与 RSC 兼容很有用。

自定义 expect 匹配器

jest-expo 为 RSC 给 Jest 的 expect 增加了几个自定义匹配器:

  • toMatchFlight:使用 Expo CLI 中渲染的伪实现来渲染一个 JSX 元素,并与 flight 字符串进行比较。
  • toMatchFlightSnapshot:与 toMatchFlight 相同,但会将 flight 字符串保存到快照文件中。

在幕后,这些方法处理了渲染 RSC 所需的部分框架运作。组件的渲染流会被缓冲成一个字符串,然后一次性进行比较。你也可以手动流式读取它,以观察渲染进度。

如果组件渲染失败,匹配器会抛出错误以使测试失败。实际上,服务端渲染器会生成一行 E:,它会被发送到客户端,从而在本地为用户抛出。

运行测试

你可以使用 test:rsc 脚本运行测试:

Terminal
yarn test:rsc --watch

如果你使用的是多 runner,可以使用 --selectProjects 标志来选择特定项目。下面的示例只运行 web 平台:

Terminal
yarn test:rsc --watch --selectProjects rsc/web

环境

在 RSC 打包环境中,你可以导入如下文件

提示

使用 server-onlyclient-only 模块来断言某个模块不应在客户端或服务端被导入:

my-module.js
import 'server-only';

RSC 默认支持包导出。你可以使用 react-server 条件来改变从模块中导入的文件:

package.json
{ "exports": { ".": { "react-server": "./index.react-server.js", "default": "./index.js" } } }

在为 RSC 打包时,所有模块都会以 React Server 模式进行打包,你可以使用 "use client" 指令来选择退出。当找到 "use client" 时,该模块会变成对客户端模块的异步引用。

"use server" 不是 "use client" 的反义词。它用于定义一个 React Server Functions 文件。