From 3af7697e932693f9cba78895889fbd551c6032c8 Mon Sep 17 00:00:00 2001 From: John Tapsell Date: Sat, 11 Feb 2023 19:30:25 -0800 Subject: [PATCH] Fix jest unit test (#1495) * Fix jest tests by mocking i18n, and prevent future such breakages by making warns and errors fatal * Delete src/setupTests.js - this is a create-react-app only file that is not used here. Setup is done in jest.setup.js --- website/jest.setup.js | 34 ++++++++++++++++++++++++++++++++++ website/src/setupTests.js | 5 ----- 2 files changed, 34 insertions(+), 5 deletions(-) delete mode 100644 website/src/setupTests.js diff --git a/website/jest.setup.js b/website/jest.setup.js index ad304f04..66be1dae 100644 --- a/website/jest.setup.js +++ b/website/jest.setup.js @@ -1,2 +1,36 @@ // jest.setup.js import "@testing-library/jest-dom/extend-expect"; + +const CONSOLE_FAIL_TYPES = ["error", "warn"]; + +// Throw errors when a `console.error` or `console.warn` happens +// by overriding the functions. +// If the warning/error is intentional, then catch it and expect for it, like: +// +// jest.spyOn(console, 'warn').mockImplementation(); +// ... +// expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('Empty titles are deprecated.')); +CONSOLE_FAIL_TYPES.forEach((type) => { + const orig_f = console[type]; + console[type] = (...message) => { + orig_f(...message); + throw new Error(`Failing due to console.${type} while running test!\n\n${message.join(" ")}`); + }; +}); + +// Mock out useTranslation hook as per https://react.i18next.com/misc/testing +jest.mock("react-i18next", () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => { + return { + t: (str) => str, + i18n: { + changeLanguage: () => new Promise(() => {}), + }, + }; + }, + initReactI18next: { + type: "3rdParty", + init: () => {}, + }, +})); diff --git a/website/src/setupTests.js b/website/src/setupTests.js deleted file mode 100644 index 1dd407a6..00000000 --- a/website/src/setupTests.js +++ /dev/null @@ -1,5 +0,0 @@ -// jest-dom adds custom jest matchers for asserting on DOM nodes. -// allows you to do things like: -// expect(element).toHaveTextContent(/react/i) -// learn more: https://github.com/testing-library/jest-dom -import "@testing-library/jest-dom";