Skip to content

Commit

Permalink
chore: ensure jest fails if a runtime error is thrown
Browse files Browse the repository at this point in the history
Use jest-fail-on-console to ensure tests fail if runtime errors are thrown,
helping prevent issues from slipping into production.

Fix jest tests which are throwing runtime errors.
  • Loading branch information
Parsium committed Oct 18, 2024
1 parent b1cd42f commit f5f90f2
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 124 deletions.
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@
"jest": "^29.5.0",
"jest-canvas-mock": "^2.5.2",
"jest-environment-jsdom": "^29.5.0",
"jest-fail-on-console": "^3.3.1",
"jest-fetch-mock": "^3.0.3",
"jest-styled-components": "^6.3.4",
"jsdom": "^21.1.0",
Expand Down
7 changes: 3 additions & 4 deletions scripts/generate_metadata/generate_metadata.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-console */
import fs from "fs";
import fetch from "node-fetch";
import semver from "semver";
Expand Down Expand Up @@ -47,7 +46,7 @@ export const writeFile = (jsonString) => {
if (err) {
throw err;
} else {
console.log("Successfully created metadata.json file.");
global.console.log("Successfully created metadata.json file.");
}
});
};
Expand All @@ -58,8 +57,8 @@ export const generateMetadata = async () => {
try {
versions = await fetchVersions();
} catch (err) {
console.error(err);
process.exit(1);
global.console.error(err);
return;
}

const formattedVersions = formatVersions(versions);
Expand Down
118 changes: 0 additions & 118 deletions scripts/generate_metadata/generate_metadata.spec.js

This file was deleted.

102 changes: 102 additions & 0 deletions scripts/generate_metadata/generate_metadata.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import fs from "fs";
import fetch from "jest-fetch-mock";
import { generateMetadata, writeFile } from "./generate_metadata";

jest.mock("fs");
const mockedFs = jest.mocked(fs);

const mockNpmVersions = {
versions: {
"98.0.0": {},
"99.0.0": {},
"100.1.1": {},
"100.2.1": {},
"101.0.0": {},
"102.0.0": {},
},
};

const mockMetadata = {
versions: {
"v102.0.0": "https://carbon.sage.com/v/102.0.0/index.html",
"v101.0.0": "https://carbon.sage.com/v/101.0.0/index.html",
"v100.2.1": "https://carbon.sage.com/v/100.2.1/index.html",
},
};

beforeEach(() => {
jest.spyOn(global.console, "log").mockImplementation(() => {});
jest.spyOn(global.console, "error").mockImplementation(() => {});

fetch.mockResponse(JSON.stringify(mockNpmVersions));

mockedFs.mkdirSync = jest.fn((path, options, callback) => {
callback();
});
mockedFs.writeFileSync = jest.fn((path, json, callback) => {
callback();
});
});

afterEach(() => {
jest.resetAllMocks();
fetch.resetMocks();
});

test("creates a metadata.json file in a metadata directory", async () => {
await generateMetadata();

expect(mockedFs.mkdirSync).toHaveBeenCalledWith(
"metadata",
{},
expect.any(Function)
);

expect(mockedFs.writeFileSync).toHaveBeenCalledWith(
"metadata/metadata.json",
JSON.stringify(mockMetadata),
expect.any(Function)
);
});

test("throws an error, when unable to create the metadata directory", () => {
mockedFs.mkdirSync = jest.fn((path, options, callback) => {
callback(new Error("An error occurred."));
});

expect(() => writeFile()).toThrow("An error occurred.");
});

test("throws an error, when unable to create the metadata.json file", () => {
mockedFs.writeFileSync = jest.fn((path, json, callback) => {
callback(new Error("An error occurred."));
});

expect(() => writeFile()).toThrow("An error occurred.");
});

describe("when unable to fetch carbon data from npm", () => {
it("logs error with http status code", async () => {
fetch.mockResponse(JSON.stringify(mockNpmVersions), {
status: 500,
ok: false,
});

await generateMetadata();

expect(global.console.error).toHaveBeenCalledWith(
new Error("Failed to fetch from npm with HTTP error code 500")
);
});

it("does not attempt to write metadata.json file", async () => {
fetch.mockResponse(JSON.stringify(mockNpmVersions), {
status: 500,
ok: false,
});

await generateMetadata();

expect(mockedFs.writeFileSync).not.toHaveBeenCalled();
});
});
7 changes: 7 additions & 0 deletions src/__spec_helper__/__internal__/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { configure } from "@testing-library/react";
import { enableFetchMocks } from "jest-fetch-mock";
import failOnConsole from "jest-fail-on-console";

import { setupMatchMediaMock } from "../mock-match-media";
import setupResizeObserverMock from "../mock-resize-observer";
import setupScrollToMock from "../mock-element-scrollto";

import "@testing-library/jest-dom";

failOnConsole({
shouldFailOnError: true,
shouldFailOnWarn: false,
});
enableFetchMocks();
setupResizeObserverMock();
setupMatchMediaMock();
Expand Down
2 changes: 1 addition & 1 deletion src/__spec_helper__/__internal__/select-test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function simulateSelectTextboxEvent(
});
resizeObserver.resize();
});
if (eventType === "focus") jest.runOnlyPendingTimers();
if (eventType === "focus") act(() => jest.runOnlyPendingTimers());
container.update();
}

Expand Down
7 changes: 6 additions & 1 deletion src/components/numeral-date/numeral-date.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1563,7 +1563,12 @@ test("should submit the form when enter key is pressed", async () => {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
const onSubmit = jest.fn();
render(
<form onSubmit={onSubmit}>
<form
onSubmit={(ev) => {
ev.preventDefault();
onSubmit(ev);
}}
>
<NumeralDate
value={{ dd: "11", mm: "11", yyyy: "2011" }}
onChange={() => {}}
Expand Down
2 changes: 2 additions & 0 deletions src/components/select/simple-select/simple-select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ describe("typing into the input", () => {

expect(screen.getByText("green", { ignore: "li" })).toBeVisible();

jest.runOnlyPendingTimers();
jest.useRealTimers();
});

Expand Down Expand Up @@ -859,6 +860,7 @@ test("does not call onOpen, when openOnFocus is true and the input is refocused

expect(onOpen).not.toHaveBeenCalled();

jest.runOnlyPendingTimers();
jest.useRealTimers();
});

Expand Down

0 comments on commit f5f90f2

Please sign in to comment.