Skip to content

Instantly share code, notes, and snippets.

@andrecalvo
Last active June 27, 2019 18:50
Show Gist options
  • Save andrecalvo/682592d690c21232b880e2c1ea7b60a9 to your computer and use it in GitHub Desktop.
Save andrecalvo/682592d690c21232b880e2c1ea7b60a9 to your computer and use it in GitHub Desktop.
import React from "react";
import { useDataApi } from "path/to/hoo/useDataApi.jsx";
import "whatwg-fetch";
import { renderHook } from "@testing-library/react-hooks";
import fetchMock from "fetch-mock";
import { act } from "react-test-renderer";
describe("useDataApi", () => {
beforeAll(() => {
global.fetch = fetch;
});
afterAll(() => {
fetchMock.restore();
});
it("should return error as true if the api error", async () => {
const { result } = renderHook(() => useDataApi());
// Tell the test that any request to 'test.com' should return return a 500 error
fetchMock.mock("test.com", 500);
// Calling the api via the `callApi` function
await act(async () => {
result.current.callApi("test.com");
});
// Data should be null and error should be true
expect(result.current.data).toBe(null);
expect(result.current.error).toBe(true);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment