R. Cooper
R. Cooper

Reputation: 21

AfterAll hook error - 'this' is not referring to my world constructor when using cucumber-js and selenium

I am getting 'AfterAll hook errored' when attempting to close my browser at the end of my tests (using cucumber-js and selenium). 'this' is not referring to world as it does in my step.js files

This is my hooks.js file:

const { AfterAll, Before } = require("cucumber");

AfterAll(async function() {
  await this.browser.close();
});

and this is my world.js file:

const driver = require("selenium-webdriver");
require("chromedriver");
const browser = new driver.Builder().forBrowser("chrome").build();
const { setWorldConstructor, setDefaultTimeout } = require("cucumber");

class CustomWorld {
  constructor() {
    this.driver = driver;
    this.browser = browser;
    this.setDefaultTimeout = setDefaultTimeout(60 * 1000);
  }
}

setWorldConstructor(CustomWorld);

Upvotes: 2

Views: 6132

Answers (2)

rawkfist0215
rawkfist0215

Reputation: 1485

Per the CucumberJS docs:

Unlike Before / After these methods will not have a world instance as this. This is because each scenario gets its own world instance and these hooks run before / after all scenarios.

It's unfortunate, as I've ran into this as well. My workaround thus far has been to declare the variable in a scope available to the beforeAll and afterAll hooks, and then import and assign that to the world object in it's file.

Upvotes: 1

Jon Acker
Jon Acker

Reputation: 31

In a JS closure this is implicitly set to whatever the outer context is (usually global). You either need to .bind() your function to this or use the fat array notation:

AfterAll(async () => {
  await this.browser.close();
});

Upvotes: 1

Related Questions