TL;DR: How can I test a function that wraps fetch with React?
I'm building a React app with TypeScript. To use the fetch api I added these libs to my tsconfig:
"lib": ["es2017", "dom"],
Now I wrote the following function:
import { Schema } from "normalizr";
import { camelizeAndNormalize } from "../../core";
export const getRequest = (fullUrlRoute: string, schema: Schema) =>
fetch(fullUrlRoute).then(response =>
response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return Promise.resolve(camelizeAndNormalize(json, schema));
})
);
The function camelizeAndNormalize
literally does what it says. (I'm normalizing my state for Redux using normalizr).
Now I wanted to test this wrapper function with the following Jest test:
import fetch from "jest-fetch-mock";
import { schema } from "normalizr";
import { getRequest } from "./getRequests";
const response = {
author: {
id: "1",
name: "Paul"
},
comments: [
{
commenter: {
id: "2",
name: "Nicole"
},
id: "324"
}
],
id: "123",
title: "My awesome blog post"
};
const expected = {
entities: {
articles: {
"123": {
author: "1",
comments: ["324"],
id: "123",
title: "My awesome blog post"
}
},
comments: {
"324": { id: "324", commenter: "2" }
},
users: {
"1": { id: "1", name: "Paul" },
"2": { id: "2", name: "Nicole" }
}
},
result: "123"
};
const fullTestUrl = "https://google.com";
const user = new schema.Entity("users");
const comment = new schema.Entity("comments", {
commenter: user
});
const testSchema = new schema.Entity("articles", {
author: user,
comments: [comment]
});
describe("get request", () => {
beforeEach(() => {
fetch.resetMocks();
});
it("calls the given fullUrlRoute and returns data", () => {
fetch.mockResponseOnce(JSON.stringify(response));
expect.assertions(3);
return getRequest(fullTestUrl, testSchema).then(res => {
expect(res).toEqual(expected);
expect(fetch.mock.calls.length).toEqual(1);
expect(fetch.mock.calls[0][0]).toEqual(fullTestUrl);
});
});
it("recognizes when a response's status is not okay", () => {
fetch.mockResponseOnce(JSON.stringify({ ok: false }), { status: 403 });
expect.assertions(1);
return getRequest(fullTestUrl, testSchema).catch(err => {
expect(err.ok).toEqual(false);
});
});
it("recognizes a failed fetch request", () => {
fetch.mockReject(new Error("fake error message"));
expect.assertions(1);
return getRequest(fullTestUrl, testSchema).catch(err => {
expect(err).toEqual(Error("fake error message"));
});
});
});
In this test I mocked fetch using jest-fetch-mock. This test throws the error though:
FAIL src/services/utils/serverRequests/GET/getRequests.test.ts
● Console
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
Why is the mock not working? How can I test a function that uses fetch in React with Jest?
Found out what I was missing out on. I needed to add the following to my src/setupTests.ts
:
// react-testing-library renders your components to document.body,
// this will ensure they're removed after each test.
// this adds jest-dom's custom assertions
import "jest-dom/extend-expect";
import "react-testing-library/cleanup-after-each";
// setupJest.js or similar file
const globalAny: any = global;
// tslint:disable-next-line
globalAny.fetch = require("jest-fetch-mock");