Skip to content

Commit

Permalink
[test] Improve stack trace for unexpected errors
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Jul 17, 2020
1 parent 750cdfe commit 7048d3e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
3 changes: 2 additions & 1 deletion test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ By default our test suite fails if any test recorded `console.error` or `console
![unexpected console.error call](./unexpected-console-error-call.png)

The failure message includes the name of the test.
The logged error is prefixed with the test file so that you can find the failing test faster (test file + test name).
The logged error is prefixed with the test file as well as suffixed with the full test name and test file.
This should help locating the test in case the top of the stack can't be read due to excessive error messages.
The error includes the logged message as well as the stacktrace of that message.
Unfortunately the stacktrace is currently duplicated due to `chai`.

Expand Down
17 changes: 15 additions & 2 deletions test/utils/setup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const formatUtil = require('format-util');
const Mocha = require('mocha');
const createDOM = require('./createDOM');

process.browser = true;
Expand All @@ -17,6 +18,7 @@ const mochaHooks = {

function throwOnUnexpectedConsoleMessages(methodName, expectedMatcher) {
const unexpectedCalls = [];
const stackTraceFilter = Mocha.utils.stackTraceFilter();

function logUnexpectedConsoleCalls(format, ...args) {
const message = formatUtil(format, ...args);
Expand All @@ -27,7 +29,7 @@ function throwOnUnexpectedConsoleMessages(methodName, expectedMatcher) {
// first line includes the (empty) error message
// i.e. Remove the `Error:` line
// second line is this frame
stack.split('\n').slice(2).join('\n'),
stackTraceFilter(stack.split('\n').slice(2).join('\n')),
message,
]);
}
Expand All @@ -49,12 +51,23 @@ function throwOnUnexpectedConsoleMessages(methodName, expectedMatcher) {
}
if (hadUnexpectedCalls) {
const location = this.currentTest.file;
const testPath = `"${this.currentTest.parent
.titlePath()
.concat(this.currentTest.title)
.join('" -> "')}"`;
const message =
`Expected test not to call console.${methodName}()\n\n` +
'If the warning is expected, test for it explicitly by ' +
`using the ${expectedMatcher}() matcher.`;

throw new Error(`${location}: ${message}\n\n${formattedCalls.join('\n\n')}`);
const error = new Error(
`${location}: ${message}\n\n${formattedCalls.join('\n\n')}\n\n` +
`in ${testPath} (${location})`,
);
// The stack of `flushUnexpectedCalls` is irrelevant.
// It includes no clue where the test was triggered
error.stack = '';
throw error;
}
});
}
Expand Down

0 comments on commit 7048d3e

Please sign in to comment.