问题
I would like to be able to access all JS warnings and errors from the Browser Console during test runs. With the "-e" (skip JS errors) flag disabled, the test stops at the first error, so clearly it is looking for them. With this flag enabled, I would like to be able to see which errors (and ideally warnings) fired during test runs.
I've tried using the ClientFunction and window.onerror methods. I've also tried the -r 'reports' flag -- I only see TestCafe errors, not JS errors from the page under test. I've tried "Accessing Console Messages" from https://devexpress.github.io/testcafe/documentation/test-api/accessing-console-messages.html but this only gives messaging thrown by console.log, etc ("Note that this method returns only messages posted via the console.error, console.warn, console.log and console.info methods. Messages output by the browser (like when an unhandled exception occurs on the page) will not be returned.")
const installErrorHandler = ClientFunction(() => {
window.onerror = error => {
console.log("ERROR::::::");
console.log(error);
};
});
Over in the Clojure space, when using the Etaoin webdriver implementation (on Chrome or Phantom.js), at any point simply performing a
(get-logs driver)
returns
{:level :warning,
:message "1,2,3,4 anonymous (:1)",
:timestamp 1511449388366,
:source nil,
:datetime #inst "2017-11-23T15:03:08.366-00:00"}
....
....
Including any 'unhandled exceptions'.
Can I not do this in TestCafe?
回答1:
Probably your example with window.onerror does not work because it executes later that error occurs. I suggest you extract the error handler into a separate *.js file and inject it using the new testcafe feature: Inject Scripts into Tested Pages.
Look at the following example:
script to inject (log-errors.js):
window.unhandledErrors = [];
window.onerror = (message, source, lineno, colno, error) => {
window.unhandledErrors.push({ message, source, lineno, colno, error });
}
test:
import { Selector } from 'testcafe';
fixture('Log errors')
.page('http://example.com')
.afterEach(async t => {
const errors = await t.eval(() => window.unhandledErrors);
console.log(errors);
});
test('test', async t => {
//...
});
Run tests by the following command:
testcafe chrome test.js -e --cs=./scripts/log-errors.js
Note that Script Injection feature is available since 1.4.0 version.
来源:https://stackoverflow.com/questions/57399515/accumulate-all-js-warnings-and-errors-during-test-runs-in-testcafe