-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test: simplify the console logging exceptions
- Loading branch information
1 parent
2e909b5
commit f7919c3
Showing
1 changed file
with
15 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())); |
f7919c3
There was a problem hiding this comment.
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