import { Fetch } from "./Fetch"; import * as fetchMock from "fetch-mock"; const ALL_METHODS: Fetch.Method[] = Object.values(Fetch.Method); const FETCH_FUNCTIONS = { [Fetch.Method.GET]: Fetch.get, [Fetch.Method.POST]: Fetch.post, [Fetch.Method.PATCH]: Fetch.patch, [Fetch.Method.PUT]: Fetch.put, [Fetch.Method.DELETE]: Fetch.delete, }; type mockRequest = { url: string; method: string; headers: Headers; credentials: RequestCredentials; redirect: RequestRedirect; body: BodyInit; }; function lastRequest(): mockRequest { const [url, options] = fetchMock.lastCall(); return { url, method: options.method, // The headers are typed as HeadersInit, but they're really a Headers object. headers: (options.headers as unknown) as Headers, credentials: options.credentials, redirect: options.redirect, body: options.body, }; } // An unfortunate quirk of fetch-mock is that it normalizes the url used in a request, // so even if the request is http://example.com it will normalize to http://example.com/. // When writing tests that check that a specific url was requested, we need to include // trailing slash even if we don't expect it to be in the request. // For convenience, we'll just always use the trailing slash in the TEST_URL. const TEST_URL = "http://example.com/"; describe("Fetch", () => { beforeEach(() => { fetchMock.reset(); Fetch.reset(); }); describe("makes requests to specified URL with the correct method", () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { fetchMock.once("*", "ok"); await FETCH_FUNCTIONS[method](TEST_URL); expect(lastRequest().url).toEqual(TEST_URL); expect(lastRequest().method).toEqual(method); }); }); }); describe("uses credentials: same-origin", () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { fetchMock.once("*", "ok"); await FETCH_FUNCTIONS[method](TEST_URL); expect(lastRequest().credentials).toEqual("same-origin"); }); }); }); describe("uses Content-Type: application/json header for methods with bodies", () => { [Fetch.Method.POST, Fetch.Method.PUT, Fetch.Method.PATCH].forEach((method) => { it(`${method} request`, async () => { fetchMock.once("*", "ok"); await FETCH_FUNCTIONS[method](TEST_URL); expect(lastRequest().headers.get("Content-Type")).toEqual("application/json"); }); }); }); describe("includes headers specified with the request", () => { [ Fetch.Method.GET, Fetch.Method.POST, Fetch.Method.PUT, Fetch.Method.PATCH, Fetch.Method.DELETE, ].forEach((method) => { it(`${method} request`, async () => { fetchMock.once("*", "ok"); const requestHeaders = { "X-test-header": "value", "X-test-2": "value2" }; await FETCH_FUNCTIONS[method](TEST_URL, {}, requestHeaders); expect(lastRequest().headers.get("X-test-header")).toEqual("value"); expect(lastRequest().headers.get("X-test-2")).toEqual("value2"); }); }); }); describe("GET request query params", () => { it("supports a single query param", async () => { fetchMock.getOnce("*", "ok"); await Fetch.get(TEST_URL, { key: "value" }); expect(lastRequest().url).toEqual(`${TEST_URL}?key=value`); }); it("supports multiple query params", async () => { fetchMock.getOnce("*", "ok"); await Fetch.get(TEST_URL, { key1: "value1", key2: "value2" }); expect(lastRequest().url).toEqual(`${TEST_URL}?key1=value1&key2=value2`); }); }); describe("request bodies", () => { describe("stringifies the body to JSON", () => { [Fetch.Method.POST, Fetch.Method.PUT, Fetch.Method.PATCH, Fetch.Method.DELETE].forEach( (method) => { it(`${method} request`, async () => { fetchMock.once(TEST_URL, "ok"); const body = { x: 5 }; await FETCH_FUNCTIONS[method](TEST_URL, body); expect(typeof lastRequest().body).toBe("string"); const bodyObject = JSON.parse(lastRequest().body as string); expect(bodyObject).toEqual(body); }); }, ); }); describe("sets the body to 'undefined' for GET and DELETE", () => { [Fetch.Method.GET, Fetch.Method.DELETE].forEach((method) => { it(`${method} request`, async () => { fetchMock.once(TEST_URL, "ok"); await FETCH_FUNCTIONS[method](TEST_URL); expect(lastRequest().body).toEqual(undefined); }); }); [Fetch.Method.DELETE].forEach((method) => { it(`${method} request`, async () => { fetchMock.once(TEST_URL, "ok"); await FETCH_FUNCTIONS[method](TEST_URL, null); expect(lastRequest().body).toEqual(undefined); }); }); }); }); describe("response bodies", () => { describe("returns an object if the response can be parsed as JSON", () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { const responseObject = { x: 5 }; fetchMock.once("*", new Response(JSON.stringify(responseObject))); const response = await FETCH_FUNCTIONS[method](TEST_URL); expect(response).toEqual(responseObject); }); }); }); describe("returns a string if the response isn't JSON", () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { const responseText = "hello world"; fetchMock.once("*", new Response(responseText)); const response = await FETCH_FUNCTIONS[method](TEST_URL); expect(response).toEqual(responseText); }); }); }); }); describe("throws an error when response is error status code", () => { [300, 404, 502].forEach((statusCode) => { describe(`${statusCode} response`, () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { const errorBody = "error body"; fetchMock.once(TEST_URL, new Response(errorBody, { status: statusCode })); try { await FETCH_FUNCTIONS[method](TEST_URL); // eslint doesn't recognize "fail", even though it works, so disable the lint rule here. // eslint-disable-next-line no-undef fail("Fetch call didn't result in an error."); } catch (err) { expect(err).toBeInstanceOf(Error); expect(err.status).toEqual(statusCode); expect(err.body).toEqual(errorBody); } }); }); }); }); }); describe.each(ALL_METHODS)("events for FetchMethod %s", (method: Fetch.Method) => { jest.useFakeTimers(); test("events include request and response information", async () => { const testBody = { x: 5 }; const testHeaders = { "X-test-header": "value", "X-test-2": "value2" }; const testResponse = new Response("ok"); const mock = jest.fn((request, response) => { // This is a bit annoying, but Fetch.Get automatically removes any trailing slashes. if (method === Fetch.Method.GET) { expect(request.url).toEqual("http://example.com"); } else { expect(request.url).toEqual(TEST_URL); } expect(request.method).toEqual(method); // Fetch.Get and Fetch.Delete don't support custom bodies or headers. if (method !== Fetch.Method.GET && method !== Fetch.Method.DELETE) { expect(request.body).toEqual(JSON.stringify(testBody)); // We can't directly compare the headers objects because Fetch adds some itself, like Content-Type. expect(request.headers.get("X-test-header")).toEqual("value"); expect(request.headers.get("X-test-2")).toEqual("value2"); } expect(response).toEqual(testResponse.clone()); }); Fetch.on(Fetch.Event.SUCCESS, mock); fetchMock.once("*", testResponse); // Fetch.Get and Fetch.Delete don't support custom bodies or headers. if (method === Fetch.Method.GET || method === Fetch.Method.DELETE) { await FETCH_FUNCTIONS[method](TEST_URL); } else { await FETCH_FUNCTIONS[method](TEST_URL, testBody, testHeaders); } jest.runAllTimers(); expect(mock).toBeCalled(); }); test("fires a SUCCESS event for a successful request", async () => { const mock = jest.fn(); Fetch.on(Fetch.Event.SUCCESS, mock); fetchMock.once("*", "ok"); await FETCH_FUNCTIONS[method](TEST_URL); jest.runAllTimers(); expect(mock).toBeCalled(); }); test("fires an ERROR event for an unsuccessful request", async () => { expect.assertions(1); const cb = jest.fn(); Fetch.on(Fetch.Event.ERROR, cb); fetchMock.once("*", new Response("error", { status: 401 })); try { await FETCH_FUNCTIONS[method](TEST_URL); } catch (err) { // do nothing - an error is expected } jest.runAllTimers(); expect(cb).toBeCalled(); }); test("allows registering multiple handlers for the same event", async () => { jest.useFakeTimers(); expect.assertions(5); const spy = jest.fn((id: string) => id); const mockEventHandler = (id: string) => () => spy(id); Fetch.on(Fetch.Event.SUCCESS, mockEventHandler("a")); Fetch.on(Fetch.Event.SUCCESS, mockEventHandler("b")); Fetch.on(Fetch.Event.ERROR, mockEventHandler("c")); Fetch.on(Fetch.Event.ERROR, mockEventHandler("d")); fetchMock.once(`${TEST_URL}success`, "ok"); fetchMock.once(`${TEST_URL}error`, new Response("error", { status: 404 })); await FETCH_FUNCTIONS[method](`${TEST_URL}success`); try { await FETCH_FUNCTIONS[method](`${TEST_URL}error`); } catch (err) { // do nothing - an error is expected } jest.runAllTimers(); expect(spy).toBeCalledTimes(4); expect(spy).toBeCalledWith("a"); expect(spy).toBeCalledWith("b"); expect(spy).toBeCalledWith("c"); expect(spy).toBeCalledWith("d"); }); }); describe("global headers", () => { it("applies constant and function global headers", async () => { const testConstantGlobalHeaders = { "x-test-1": "1", "x-test-2": "2", "x-test-3": "3", }; const keys = Object.keys(testConstantGlobalHeaders); keys.forEach((header) => { Fetch.setGlobalHeader(header, testConstantGlobalHeaders[header]); }); Fetch.setGlobalHeader("x-simple-function", () => "simple-result"); Fetch.setGlobalHeader("x-requested-url", (request) => request.url); fetchMock.once("*", "ok"); await Fetch.post(TEST_URL); keys.forEach((header) => { expect(lastRequest().headers.get(header)).toEqual(testConstantGlobalHeaders[header]); }); expect(lastRequest().headers.get("x-simple-function")).toEqual("simple-result"); expect(lastRequest().headers.get("x-requested-url")).toEqual(TEST_URL); }); it("doesn't include function headers that evaluate to falsey values", async () => { Fetch.setGlobalHeader("x-empty", () => ""); Fetch.setGlobalHeader("x-null", () => null); Fetch.setGlobalHeader("x-undefined", () => undefined); fetchMock.once("*", "ok"); await Fetch.post(TEST_URL); expect(lastRequest().headers.has("x-empty")).toEqual(false); expect(lastRequest().headers.has("x-null")).toEqual(false); expect(lastRequest().headers.has("x-undefined")).toEqual(false); }); it("passes all request info into function global headers", async () => { const testBody = { x: 5 }; const testHeaders = { "x-header": "value" }; Fetch.setGlobalHeader("x-test", (request) => { expect(request.url).toEqual(TEST_URL); expect(request.body).toEqual(JSON.stringify(testBody)); expect(request.method).toEqual(Fetch.Method.POST); expect(request.headers.get("x-header")).toEqual("value"); return "value"; }); fetchMock.once("*", "ok"); await Fetch.post(TEST_URL, testBody, testHeaders); expect(lastRequest().headers.get("x-test")).toEqual("value"); }); it("includes global headers in event handlers input", async () => { jest.useFakeTimers(); const mockEventHandler = jest.fn((request) => { expect(request.headers.get("x-test")).toEqual("value"); }); Fetch.setGlobalHeader("x-test", "value"); Fetch.on(Fetch.Event.SUCCESS, mockEventHandler); fetchMock.once("*", "ok"); await Fetch.post(TEST_URL); jest.runAllTimers(); expect(mockEventHandler).toBeCalled(); }); it("only uses global headers for the specified methods", async () => { const testHeaders = ["x-test", "x-test-2"]; Fetch.setGlobalHeader(testHeaders[0], "value", [Fetch.Method.PUT, Fetch.Method.POST]); Fetch.setGlobalHeader(testHeaders[1], "value", [Fetch.Method.GET]); const expectedHeaders = { [Fetch.Method.PUT]: testHeaders[0], [Fetch.Method.POST]: testHeaders[0], [Fetch.Method.GET]: testHeaders[1], }; fetchMock.mock("*", "ok"); ALL_METHODS.forEach((method) => { FETCH_FUNCTIONS[method](TEST_URL); testHeaders.forEach((header) => { const isExpected = expectedHeaders[method] === header; expect(lastRequest().headers.has(header)).toEqual(isExpected); }); }); }); it("request specific headers take priority over global headers", async () => { Fetch.setGlobalHeader("x-test", "global-value"); fetchMock.once("*", "ok"); await Fetch.post(TEST_URL, {}, { "x-test": "request-value" }); expect(lastRequest().headers.get("x-test")).toEqual("request-value"); }); }); describe("applies global request options with each request", () => { ALL_METHODS.forEach((method) => { it(`${method} request`, async () => { Fetch.setGlobalOptions({ credentials: "omit", redirect: "error", }); fetchMock.once("*", "ok"); await FETCH_FUNCTIONS[method](TEST_URL); expect(lastRequest().credentials).toEqual("omit"); expect(lastRequest().redirect).toEqual("error"); }); }); }); });