Skip to content

Commit

Permalink
docs(example): Remix + MSW example (#2156)
Browse files Browse the repository at this point in the history
Co-authored-by: Kent C. Dodds <[email protected]>
  • Loading branch information
Girish21 and kentcdodds authored Mar 9, 2022
1 parent ad77263 commit 67df1c9
Show file tree
Hide file tree
Showing 13 changed files with 11,652 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/msw/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules

/.cache
/build
/public/build
37 changes: 37 additions & 0 deletions examples/msw/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Remix + MSW

This example demonstrates [MSW's][msw] usage with Remix to mock any HTTP calls from the Remix server during development.

## Preview

Open this example on [CodeSandbox](https://codesandbox.com):

[![Open in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/remix-run/remix/tree/main/examples/msw)

## Example

- If the API is still under development and we don't want to wait for the API to be completed.
- We want to simulate various edge and error cases of making an HTTP call and check how the app handles these cases.
- If the external APIs are metered and charged for the number of API calls made, it's pretty easy to burst through the API quota during development.
- We need an active network during development if we rely on external HTTP calls for the app to work. For some, this may be an issue.

We can mock the HTTP calls using MSW, which intercepts the API calls from the server and returns a mocked response.

You can read more about the use cases of MSW [here](https://mswjs.io/docs/#when-to-mock-api)

## Gotchas

MSW currently does not support intercepting requests made by [undici](https://undici.nodejs.org/#/). For local development, Cloudflare Workers and Pages simulates the production environment using [wrangler](https://developers.cloudflare.com/workers/cli-wrangler), which intern runs [miniflare](https://github.com/cloudflare/miniflare). `Miniflare` implements `fetch` using `undici` instead of `node-fetch`. You can follow this issue [#159](https://github.com/mswjs/interceptors/issues/159) to track the progress.

## Relevant files

- [mocks](./mocks/index.js) - registers the Node HTTP mock server
- [handlers](./mocks/handlers.js) - describes the HTTP mocks
- [root](./app/root.tsx)
- [package.json](./package.json)

## Related Links

[MSW][msw]

[msw]: https://mswjs.io/
4 changes: 4 additions & 0 deletions examples/msw/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";

hydrate(<RemixBrowser />, document);
21 changes: 21 additions & 0 deletions examples/msw/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { renderToString } from "react-dom/server";
import { RemixServer } from "remix";
import type { EntryContext } from "remix";

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
const markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);

responseHeaders.set("Content-Type", "text/html");

return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders,
});
}
39 changes: 39 additions & 0 deletions examples/msw/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { LoaderFunction } from "remix";
import { useLoaderData } from "remix";
import { json } from "remix";
import { Links, LiveReload, Meta, Scripts, ScrollRestoration } from "remix";

type LoaderData = { message: string };

export const loader: LoaderFunction = async () => {
const data = await fetch("https://my-mock-api.com").then((response) =>
response.json()
);

if (!data || typeof data.message !== "string") {
throw json({ message: "Server error" }, { status: 500 });
}

return json<LoaderData>(data);
};

export default function App() {
const loaderData = useLoaderData<LoaderData>();

return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<h1>{loaderData.message}</h1>
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
9 changes: 9 additions & 0 deletions examples/msw/mocks/handlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { rest } = require("msw");

const handlers = [
rest.get("https://my-mock-api.com", (_, res, ctx) => {
return res(ctx.status(200), ctx.json({ message: "from msw" }));
}),
];

module.exports = handlers;
6 changes: 6 additions & 0 deletions examples/msw/mocks/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const { setupServer } = require("msw/node");
const handlers = require("./handlers");

const server = setupServer(...handlers);
server.listen({ onUnhandledRequest: "warn" });
console.info("MSW initialised");
Loading

0 comments on commit 67df1c9

Please sign in to comment.