Skip to Content
Testing

Use a hand-written HttpClient

Fake the transport with your own HttpClient, for a network failure or a body that arrives slowly or breaks off.

The fake backend covers most tests, slow responses included. Two things are out of its reach: a request that never gets a response, since a handler can't fail, and a body that arrives in pieces or breaks off partway, since the fake backend sends each body in one piece. For those, you provide an HttpClient of your own, which answers however you need. This page shows how, with a sample for each case.

Provide your own HttpClient

Effetch sends every request through the HttpClient layer you provide, so a test can provide one made with HttpClient.make. Its function gets each request and its URL, and returns the response. The following client records each request and answers with a todo:

import * as  from "effect/Effect";
import * as  from "effect/http/HttpClient";
import * as  from "effect/http/HttpClientResponse";
import * as  from "effect/Layer";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

const  = .({ : ., : . });

class  extends .<>()("Api", {
  : "https://api.test",
}) {}

const : <string> = [];

const  = .(
  .,
  .((, ) => {
    .(`${.} ${.}`);
    return .(
      .(
        ,
        .({ : 1, : "Write docs" }),
      ),
    );
  }),
);

const  = .(function* () {
  const  = yield* ;
  return yield* .("/todos/:id", { : { : 1 }, :  });
});

const  = await .(
  .(.(..(.()))),
);
// todo: { id: 1, title: "Write docs" }; sent: ["GET https://api.test/todos/1"]

HttpClientResponse.fromWeb turns a standard Response into Effect's response, so you can build the answer with anything Response accepts.

Fail with a network error

To test how your code handles a request that gets no response, such as when the device is offline, fail with a transport error. Effetch turns it into a NetworkError, as it does when fetch itself fails:

import * as  from "effect/Effect";
import * as  from "effect/http/HttpClient";
import * as  from "effect/http/HttpClientError";
import * as  from "effect/Layer";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

const  = .({ : ., : . });

class  extends .<>()("Api", {
  : "https://api.test",
}) {}

// Every request fails, as if the device were offline
const  = .(
  .,
  .(() =>
    .(
      new .({
        : new .({
          ,
          : new ("Failed to fetch"),
        }),
      }),
    ),
  ),
);

const  = .(function* () {
  const  = yield* ;
  return yield* .("/todos/:id", { : { : 1 }, :  });
}).(
  .("NetworkError", () =>
    .(`${.} (${(.)})`),
  ),
);

const  = await .(
  .(.(..(.()))),
);
// "GET https://api.test/todos/1: network error (TypeError: Failed to fetch)"

The NetworkError carries the request's method and URL, and its cause is the cause you gave the TransportError. Only a TransportError becomes a NetworkError. A StatusCodeError is handled as the response it carries, and any other reason, such as an InvalidUrlError, makes the call die as a defect.

Send a body that breaks off

To test a stream that slows down or drops partway, answer with a Response whose body is a ReadableStream you control. The following client sends one line of newline-delimited JSON, waits, then breaks the connection:

import * as  from "effect/Effect";
import * as  from "effect/http/HttpClient";
import * as  from "effect/http/HttpClientResponse";
import * as  from "effect/Layer";
import * as  from "effect/Schema";
import * as  from "effect/Stream";

import {  } from "@monarcode/effetch";

const  = .({ : . });

class  extends .<>()("Api", {
  : "https://api.test",
}) {}

const  = new ();

// One value, a pause, then the connection drops
const  = () =>
  new <>({
    async () {
      .(.('{"percent":50}\n'));
      await new (() => (, 200));
      .(new ("Connection reset"));
    },
  });

const  = .(
  .,
  .(() =>
    .(
      .(
        ,
        new ((), {
          : { "content-type": "application/x-ndjson" },
        }),
      ),
    ),
  ),
);

const  = .(function* () {
  const  = yield* ;
  yield* 
    .("/jobs/1/progress", { :  })
    .(.(() => .(.)));
}).(.("DecodeError", () => .(.)));

await .(
  .(.(..(.()))),
);
// Logs 50, then, 200 ms later:
// "Failed to read the response body: Connection reset"

Your code gets the first value as soon as it arrives. When the body breaks off, the stream fails with a DecodeError. To test a slow stream that ends normally, call controller.close() instead of controller.error(…). For an SSE endpoint, send content-type: text/event-stream, since api.sse checks it.

What's next

On this page