// A plain-JS model of MSW's handler list, not the library itself.
const http = {
get: (path, resolver) => ({ method: "GET", path, resolver }),
};
function setupServer(...initialHandlers) {
let handlers = [...initialHandlers];
return {
use(...extra) {
handlers = [...extra, ...handlers];
},
resetHandlers() {
handlers = [...initialHandlers];
},
async request(method, path) {
for (const handler of handlers) {
if (handler.method !== method || handler.path !== path) continue;
const response = handler.resolver();
if (response) return response;
}
throw new Error(`unhandled ${method} ${path}`);
},
};
}
const server = setupServer(
http.get("/tasks", () => ({ status: 200, body: ["Write the release notes"] })),
);
async function test(name, fn) {
try {
console.log(name + ": " + (await fn()));
} catch (error) {
console.log(name + ": " + error.message);
} finally {
server.resetHandlers();
}
}
await test("list", async () => (await server.request("GET", "/tasks")).status);
await test("error", async () => {
server.use(http.get("/tasks", () => ({ status: 500, body: [] })));
return (await server.request("GET", "/tasks")).status;
});
await test("fallthrough", async () => {
server.use(http.get("/tasks", () => undefined));
return (await server.request("GET", "/tasks")).status;
});
await test("profile", async () => (await server.request("GET", "/me")).status);