createRemixStub
此工具可讓您透過設定模擬的一組路由來單元測試您自己的、依賴 Remix 掛鉤/元件的元件。
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("..."));
});
如果您的 loader
依賴 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 }} />);