Skip to content

Commit

Permalink
test: simplify the console logging exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
AdeAttwood committed Mar 17, 2023
1 parent 2e909b5 commit f7919c3
Showing 1 changed file with 15 additions and 31 deletions.
46 changes: 15 additions & 31 deletions jest.setup.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,19 @@
const consoleErrorMock = jest.spyOn(console, "error");
const consoleWarnMock = jest.spyOn(console, "warn");

function getMessageForMock(prefix: string, calls: Array<Array<string>>) {
const messages: { [k: string]: number } = {};
for (const [message] of calls) {
if (!(message in messages)) {
messages[message] = 0;
}

messages[message]++;
/**
* Throws an error amending the call stack to remove the first call. This is to
* trick the react console logger into thinking the call came one call earlier.
* Then it will print out a much more logical errors and code snippets.
*/
function throwError(error: Error) {
if (!error.stack) {
throw new Error("Error must have a stack");
}

return Object.entries(messages)
.map(([message, count]) => `${prefix} (${count}x): ${message}`)
.join("\n")
.trim();
}
const lines = error.stack.split("\n");
lines.splice(1, 1);
error.stack = lines.join("\n");

beforeEach(() => {
consoleErrorMock.mockReset();
consoleWarnMock.mockReset();
});
afterAll(() => {
consoleErrorMock.mockRestore();
consoleWarnMock.mockRestore();
});
throw error;
}

afterEach(() => {
const errors = getMessageForMock("ERROR", consoleErrorMock.mock.calls);
const warnings = getMessageForMock("WARNING", consoleWarnMock.mock.calls);
if (errors || warnings) {
throw new Error(`Console must not throw errors or warnings\n\n${errors}\n${warnings}`);
}
});
jest.spyOn(console, "error").mockImplementation(() => throwError(new Error()));
jest.spyOn(console, "warn").mockImplementation(() => throwError(new Error()));

1 comment on commit f7919c3

@vercel
Copy link

@vercel vercel bot commented on f7919c3 Mar 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

react-form – ./

react-form-sandy.vercel.app
react-form-git-0x-adeattwood.vercel.app
react-form-adeattwood.vercel.app

Please sign in to comment.