0

We are using Testcafe for our regression tests and I would like to enhance the test logging of failed asserts by adding any messages from the browser console to the output. According to the Testcafe documentation, this code will print "The test has failed" in case the given element is not visible on the page:

await t.expect(Selector('#elementId').visible).ok("The test has failed");

According to the doco, the browser console messages can be read using the the t.getBrowserConsoleMessages method, but I have not been able to combine them into one statement like e.g.

await t.expect(Selector('#elementId').visible).ok(console.log(await t.getBrowserConsoleMessages()));

as this always processes the getBrowserConsoleMessages method and outputs the console messages, regardless of whether the assert is successful or not.

Is there a way to make this work only if the assert fails?

Holger
  • 23
  • 3
  • Update: I think I found an answer. The approach described in https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string seems to work. – Holger Sep 02 '21 at 10:09

2 Answers2

2

I seems you just need to call getBrowserConsoleMessages conditionally. To get the expected behavior, you can use the following code:

import { Selector } from 'testcafe';

fixture`A set of examples that illustrate how to use TestCafe API`
    .page`http://devexpress.github.io/testcafe/example/`;

test('Test1', async t => {
    
    const isVisible = await Selector('#developer-name').visible;
    if (!isVisible)
        console.log(await t.getBrowserConsoleMessages())
    await t.expect(isVisible).ok();
});

test('Test2', async t => {
    
    const isVisible = await Selector('#developer-name2').visible;
    if (!isVisible)
        console.log(await t.getBrowserConsoleMessages())
    await t.expect(isVisible).ok();
});
Pavel Avsenin
  • 254
  • 1
  • 2
  • That might work but it looks like it may blow up the code in case of a large number of asserts. – Holger Sep 04 '21 at 00:41
0

Here is how I got this working myself:

import { Selector } from 'testcafe';

async function objToString (obj) {
  return Object.entries(obj).reduce((str, [p, val]) => {
      return `${str}${p}::${val}\n`;
  }, '');
}

fixture('My test')
  .page('https://myurl.com')

test('Test1', async t => {
    ....
    await t.expect(Selector('#elementId').visible).ok(await objToString(await browser.getBrowserConsoleMessages()));
    ....
});
Holger
  • 23
  • 3