For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt, and this page is available as Markdown at /next/zh/api/react/testing-library/index.md.
Lynx
  • 简体中文
  • @lynx-js/react/testing-library

    ReactLynx Testing Library 是一个简单而完备的 ReactLynx 单元测试库,鼓励良好的测试实践。

    完全受 react-testing-library 启发

    和 react-testing-library 一样,这个库的设计目标是让你用测试 React 组件的方式来测试 ReactLynx 组件。

    Setup

    Rstest

    用 @lynx-js/react/testing-library/rstest-config 配置 rstest。

    推荐库项目使用:

    import { defineConfig } from '@rstest/core';
    import { withDefaultConfig } from '@lynx-js/react/testing-library/rstest-config';
    
    export default defineConfig({
      extends: withDefaultConfig(),
    });

    想复用应用的 lynx.config.ts 时,使用 withLynxConfig:

    // rstest.config.ts
    import { defineConfig } from '@rstest/core';
    import { withLynxConfig } from '@lynx-js/react/testing-library/rstest-config';
    
    export default defineConfig({
      extends: withLynxConfig(),
    });

    withLynxConfig 和 withDefaultConfig 的区别:

    • withLynxConfig:面向应用。读取你的 lynx.config.ts 并转换成 rstest 配置,让 rspeedy/lynx 的设置在测试中同样生效。
    • withDefaultConfig:面向库。只应用 testing-library 的默认配置(jsdom、setup 文件、全局变量),其余部分由你通过 modifyRstestConfig 提供。

    然后就可以开始写测试,并用 rstest 运行它们了!

    更多用法详见 https://rstest.rs/

    Vitest

    配置 vitest:

    import { defineConfig } from 'vitest/config';
    import { vitestTestingLibraryPlugin } from '@lynx-js/react/testing-library/plugins';
    
    export default defineConfig({
      plugins: [
        vitestTestingLibraryPlugin(),
      ],
      test: {
        // ...
      },
    });

    然后就可以开始写测试,并用 vitest 运行它们了!

    createVitestConfig 仍然可用以保持向后兼容,但已废弃。

    Usage

    import '@testing-library/jest-dom';
    import { test, expect } from 'vitest'; // or '@rstest/core'
    import { render } from '@lynx-js/react/testing-library';
    
    test('renders options.wrapper around node', async () => {
      const WrapperComponent = ({ children }) => (
        <view data-testid='wrapper'>{children}</view>
      );
      const Comp = () => {
        return <view data-testid='inner' style='background-color: yellow;' />;
      };
      const { container, getByTestId } = render(<Comp />, {
        wrapper: WrapperComponent,
      });
      expect(getByTestId('wrapper')).toBeInTheDocument();
      expect(container.firstChild).toMatchInlineSnapshot(`
        <view
          data-testid="wrapper"
        >
          <view
            data-testid="inner"
            style="background-color: yellow;"
          />
        </view>
      `);
    });

    💡 由于我们的测试环境(@lynx-js/testing-environment)基于 jsdom,你可能还想安装 @testing-library/jest-dom,以便使用这些自定义 jest matcher。

    Examples

    更多用法参见我们的示例。

    Credits

    • Testing Library,提供了测试工具和 React 测试的良好实践。

    命名空间

    类

    接口

    类型别名

    变量

    函数

    除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。