@@ -112,7 +112,8 @@ pnpm add twd-js
112112
113113## Mock Service Worker (API Mocking )
114114
115- TWD provides a CLI to easily set up a mock service worker for API / request mocking in your app .
115+
116+ TWD provides a CLI to easily set up a mock service worker for API / request mocking in your app . You do ** not ** need to manually register the service worker in your app —TWD handles this automatically when you use ` twd.initRequestMocking() ` in your tests .
116117
117118### Install the mock service worker
118119
@@ -127,14 +128,27 @@ npx twd-mock init <public-dir> [--save]
127128
128129This will copy ` mock-sw.js ` to your public directory .
129130
130- ### Register the service worker in your app
131-
132- Add this snippet to your app ' s entry point (e.g., `main.tsx`):
133131
134- ` ` ` js
135- if ("serviceWorker" in navigator) {
136- navigator.serviceWorker.register("/mock-sw.js?v=1");
137- }
132+ ### How to use request mocking in your tests
133+
134+ Just call ` await twd.initRequestMocking() ` at the start of your test , then use ` twd.mockRequest ` to define your mocks . Example :
135+
136+ ` ` ` ts
137+ it("fetches a message", async () => {
138+ await twd.initRequestMocking();
139+ await twd.mockRequest("message", {
140+ method: "GET",
141+ url: "https://api.example.com/message",
142+ response: {
143+ value: "Mocked message!",
144+ },
145+ });
146+ const btn = await twd.get("button[data-twd='message-button']");
147+ btn.click();
148+ await twd.waitForRequest("message");
149+ const messageText = await twd.get("p[data-twd='message-text']");
150+ messageText.should("have.text", "Mocked message!");
151+ });
138152` ` `
139153
140154-- -
0 commit comments