Search code examples
cucumberwebdriver-iocucumberjs

How to use tags in hooks on cucumberjs with webdriverio?


I want to have a new clean session after each of my tests. In order to do that I use reloadSession() in an afterScenario hook

 afterScenario: ({tags: 'not @last'}, async function (world,result) {
        await browser.reloadSession();
    })

However, I don't want this hook triggered on the last scenario (I don't want an extra session to reload if it's not needed) so I tagged my last test on the feature file as @last.

  @last
  Scenario: An anonymous user cannot login with the wrong credentials
    Given I am on the 'login' page
    When I login with invalid credentials
      | username  | password      |
      | wrongUser | wrongPassword |
    Then I should the following error message
      | error                                        |
      | Error: Incorrect login or password provided. |

When I try to do this and run the hook for all the tests without the @last tag, nothing happens. What am I doing wrong here?


Solution

  • This we can handle in 2 ways:

    1. Use ~ instead of not like (May or May not work):

      afterScenario: ({tags: '~@last'}, async function (world,result) { await browser.reloadSession(); });

    2. Take 'scenario' as parameter to this async function like this:

      afterScenario: (async function (world,result, scenario) { let isLastTag; scenario.pickle.tags.forEach(tag => { isLastTag = tag.equals("@last"); });

               if (!isLastTag)
               await browser.reloadSession();
      

      });

    While executing, cucumberjs stores complete scenario info in 'scenario' and using that, we can filter out like above