主分支
分支
主分支 (2.15.2)dev
版本
2.15.21.19.3v0.21.0
React Router v7 已经发布。 查看文档
createRemixStub

createRemixStub

此实用程序允许您通过设置模拟的路由集来单元测试依赖于 Remix hooks/components 的组件

import { createRemixStub } from "@remix-run/testing";

test("renders loader data", async () => {
  const RemixStub = createRemixStub([
    {
      path: "/",
      meta() {
        /* ... */
      },
      links() {
        /* ... */
      },
      Component: MyComponent,
      ErrorBoundary: MyErrorBoundary,
      action() {
        /* ... */
      },
      loader() {
        /* ... */
      },
    },
  ]);

  render(<RemixStub />);

  // Assert initial render
  await waitFor(() => screen.findByText("..."));

  // Click a button and assert a UI change
  user.click(screen.getByText("button text"));
  await waitFor(() => screen.findByText("..."));
});

如果您的 loaders 依赖于 getLoadContext 方法,您可以通过 createRemixStub 的第二个参数提供一个存根上下文

const RemixStub = createRemixStub(
  [
    {
      path: "/",
      Component: MyComponent,
      loader({ context }) {
        return json({ message: context.key });
      },
    },
  ],
  { key: "value" }
);

如果您需要控制初始 URL、历史堆栈、水合数据或未来标志,则 <RemixStub> 组件本身采用类似于 React Router 的属性

// Test the app rendered at "/2" with 2 prior history stack entries
render(
  <RemixStub
    initialEntries={["/", "/1", "/2"]}
    initialIndex={2}
  />
);

// Test the app rendered with initial loader data for the root route.  When using
// this, it's best to give your routes their own unique IDs in your route definitions
render(
  <RemixStub
    hydrationData={{
      loaderData: { root: { message: "hello" } },
    }}
  />
);

// Test the app rendered with given future flags enabled
render(<RemixStub future={{ v3_coolFeature: true }} />);
文档和示例根据以下许可 MIT