Skip to content

Commit

Permalink
docs: How to use MSW? (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
uki00a committed Nov 23, 2023
1 parent 064c385 commit 15ac6ba
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,52 @@ import {

import { expect } from "$fresh-testing-library/expect.ts";
```

## Recipes

### Testing a component which uses relative `fetch()`

By combining [MSW](https://github.com/mswjs/msw) and `--___location` flag, you can
test a component which calls `fetch()` with a relative URL.

First, add the following lines to `deno.json`:

```jsonc
{
"imports": {
// Add the following lines:
"msw": "npm:[email protected]",
"msw/node": "npm:[email protected]/node"
}
}
```

Then you can use MSW as follows:

```ts
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { expect } from "$fresh-testing-library/expect.ts";
import { afterAll, beforeAll, describe, it } from "$std/testing/bdd.ts";

// You should pass `--___location` flag.
expect(___location).toBeTruthy();

describe("msw", () => {
const server = setupServer(
http.get(`${___location.origin}/api/user`, () =>
HttpResponse.json({
id: 1,
name: "foo",
})),
);

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterAll(() => server.close());

it("can be used to intercept requests", async () => {
const res = await fetch("/api/user");
expect(await res.json()).toEqual({ id: 1, name: "foo" });
});
});
```
4 changes: 3 additions & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"update": "deno run -A -r https://fresh.deno.dev/update .",
"check": "deno fmt --check && deno lint && deno task check:imports",
"check:imports": "deno run --allow-read tools/check_imports.ts",
"test": "deno test --allow-read --allow-env --allow-write=.doctest.ts,.doctest.tsx --allow-net=esm.sh,deno.land --allow-run=deno --doc",
"test": "deno test --allow-read --allow-env --allow-write=.doctest.ts,.doctest.tsx --allow-net=esm.sh,deno.land --allow-run=deno --doc --___location=http://localhost:3000",
"build": "deno run -A demo/dev.ts build",
"preview": "deno run -A demo/main.ts"
},
Expand All @@ -28,6 +28,8 @@
"$fresh-testing-library": "./mod.ts",
"$fresh-testing-library/": "./",
"$gfm": "https://deno.land/x/[email protected]/mod.ts",
"msw": "npm:[email protected]",
"msw/node": "npm:[email protected]/node",
"__TODO(#58)__": "The following line should be removed once [email protected] is released.",
"preact-render-to-string": "https://esm.sh/*[email protected]"
},
Expand Down

0 comments on commit 15ac6ba

Please sign in to comment.