Marques Woodson
Marques Woodson

Reputation: 497

In TestCafe is there a way to know if the test passed or failed in after hook?

I am trying to mark tests as pass/failed through a rest API (Zephyr) while my testcafe tests are running. I was wondering if it's possible in the after or afterEach hook to know if the test passed/failed so that I can run some script based on the result.

Something like:

test(...)
.after(async t => {
  if(testFailed === true) { callApi('my test failed'); }
})

Upvotes: 3

Views: 2687

Answers (2)

ds4940
ds4940

Reputation: 3672

This can be determined from the test controller, which has more information nested within it that is only visible at run time. An array containing all the errors thrown in the test is available as follows

t.testRun.errs

If the array is populated, then the test has failed.

Upvotes: 1

Alex Kamaev
Alex Kamaev

Reputation: 6318

I see two ways in which to solve your task. First, do not subscribe to the after hook, but create your own reporter or modify the existing reporter. Please refer to the following article: https://devexpress.github.io/testcafe/documentation/extending-testcafe/reporter-plugin/#implementing-the-reporter   The most interesting method there is reportTestDone because it accepts errs as a parameter, so you can add your custom logic there.

The second approach is using sharing variables between hooks and test code

You can write your test in the following manner:

test(`test`, async t => {
    await t.click('#non-existing-element');

    t.ctx.passed = true;
}).after(async t => {
    if (t.ctx.passed)
        throw new Error('not passed');
});

Here I am using the shared passed variable between the test code and hook. If the test fails, the variable will not be set to true, and I'll get an error in the after hook.

Upvotes: 6

Related Questions