Skip to content
FrontDepth, Home

Back to the topic

Practice: Mocking the network and modules

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

3 predict-output · 4 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputMiddle

    This is a plain-JS model of MSW's handler list, not the library: use() prepends handlers, a request goes to the first matching handler that returns a response, resetHandlers() runs after every test, and an unmatched request throws, like onUnhandledFrame: "error". What does it log?

    JavaScript
    // 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);
  2. Predict the outputMiddle

    serverError and networkError stand in for two MSW handlers: one answers with a 500, the other behaves like HttpResponse.error(), which makes fetch reject with a TypeError. The responses are real Response objects. What does it log?

    TypeScript
    type Fetch = (url: string) => Promise<Response>;
    
    // Stand-ins for what MSW handlers would answer.
    const serverError: Fetch = async () =>
      Response.json({ message: "Database is down" }, { status: 500 });
    const networkError: Fetch = async () => {
      throw new TypeError("Failed to fetch");
    };
    
    async function loadTasks(fetchImpl: Fetch): Promise<string> {
      try {
        const response = await fetchImpl("https://api.example.com/tasks");
        const tasks: unknown = await response.json();
        return "rendered " + JSON.stringify(tasks);
      } catch (error) {
        return "error state: " + (error as Error).message;
      }
    }
    
    async function loadTasksChecked(fetchImpl: Fetch): Promise<string> {
      try {
        const response = await fetchImpl("https://api.example.com/tasks");
        if (!response.ok) throw new Error("HTTP " + response.status);
        const tasks: unknown = await response.json();
        return "rendered " + JSON.stringify(tasks);
      } catch (error) {
        return "error state: " + (error as Error).message;
      }
    }
    
    console.log(await loadTasks(serverError));
    console.log(await loadTasks(networkError));
    console.log(await loadTasksChecked(serverError));
    console.log(await loadTasksChecked(networkError));
  3. Open questionMiddle

    In a component test, where would you mock the network, and why not mock your own API module or fetch?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  4. Open questionMiddle

    How do you test the loading, empty and error states of a component that fetches data?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  5. Predict the outputSenior

    This snippet loads a real ES module from a data: URL, so it runs without Vitest. completeTask calls track inside the module. The script tries to replace track on the module namespace, then on a plain object copied from it, the way a test tool might patch an export. What does it log?

    JavaScript
    // A real ES module, loaded from a data: URL so it fits in one snippet.
    const source = `
    export let sent = 0;
    export function track(name) {
      sent += 1;
      return "real " + name;
    }
    export function completeTask(id) {
      return track("task_completed:" + id);
    }
    `;
    const analytics = await import("data:text/javascript," + encodeURIComponent(source));
    
    console.log(analytics.completeTask("t1"));
    console.log(analytics.sent);
    
    try {
      analytics.track = () => "fake";
    } catch (error) {
      console.log(error.constructor.name);
    }
    
    // A plain object with the same exports, which a tool could patch.
    const patchable = { ...analytics };
    patchable.track = () => "fake";
    console.log(patchable.track("x"));
    console.log(patchable.completeTask("t2"));
    console.log(analytics.sent);
  6. Open questionSenior

    Why can vi.spyOn on a named export fail to affect the code under test, and what do you do instead?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  7. Open questionSenior

    What is contract drift between mocks and the real API, and how do you catch it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.