Stubbing / Spy on global.fetch in Deno

Viewed 294

I'm just getting into Deno, one of the things I'm a little unsure about is how to stub or create a spy for the global fetch function?

One solution is to simply wrap the fetch in a function which itself can by stubbed or spied on, but that seems like an unnecessary abstraction.

Any help would be much appreciated.

1 Answers

With denock you can mock the return object of the fetch call. Maybe not what you want but now you can test without a real call to the server.

https://deno.land/x/denock@0.2.0


import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import { denock } from "https://deno.land/x/denock/mod.ts";

// function to test
async function fetchFromServer() {
  const urlObject = new URL("https://jsonplaceholder.typicode.com/todos");

  const response = await fetch(urlObject, {
    method: "POST",
    headers: new Headers({
      "content-type": "application/json",
    }),
    body: JSON.stringify({
      userId: 2,
      id: 23024,
      title: "delectus aut autem",
      completed: false,
    }),
  });

  return await response.json();
}

// mock return
denock({
  method: "POST",
  protocol: "https",
  host: "jsonplaceholder.typicode.com",
  headers: [
    {
      header: "content-type",
      value: "application/json",
    },
  ],
  path: "/todos",
  requestBody: {
    userId: 2,
    id: 23024,
    title: "delectus aut autem",
    completed: false,
  },
  replyStatus: 201,
  responseBody: { example: "My mocked response" },
});


// test
Deno.test("fetch", async () => {
  const actual = await fetchFromServer();
  assertEquals({ example: "My mocked response" }, actual);
});




Related