我如何在 CucumberJS 中跨多个步骤定义文件共享我的 World 实例?

How do i share my World instance across multiple step definition files in CucumberJS?

我正在实施一个 CucumberJS 方案,该方案在两个不同的步骤定义文件中使用多个步骤。第一步在世界上设置一些变量,其他步骤定义文件中的步骤必须使用这些变量。

变量设置正确,但当其他文件上的步骤尝试读取它时,它是未定义的。除了合并步骤定义文件之外,还有其他解决方法吗?

示例:

world.js

var World = function World() {
  this.client = '';
};

module.exports.World = World;

test.feature

Given a variable A
Then some other step

step1.steps.js

module.exports = function () {
    this.World = require(process.cwd() + '/test/features/support/world').World;

    this.Given(/^a Variable A$/, function () {
        this.client = 'abc';
    });
};

step2.steps.js

module.exports = function () {
    this.World = require(process.cwd() + '/test/features/support/world').World;

    this.Then(/^some other step$/, function () {
        console.log(this.client);
    });
};

您可以直接参数化您的 test.feature :

Given a variable "abc"
Then some other step

现在在您的步骤中传递此变量

step1.steps.js

module.exports = function() {
  this.World = require(process.cwd() + '/test/features/support/world').World;

  this.Given(/^a Variable "([^"]*)"$/, function(variable) {
    this.client = variable;
  });
};

step2.steps.js

module.exports = function() {
  this.World = require(process.cwd() + '/test/features/support/world').World;

  this.Then(/^some other step$/, function() {
    console.log(this.client); // would print abc
  });
};

您正在设置 this.client 而不是 this.World.client。此外,您应该在 world.js:

中使用对象而不是构造函数

world.js

module.exports = {
    client: ''
};

step1.steps.js

var world = require('./test/features/support/world.js');

module.exports = function () {
    this.Given(/^a Variable A$/, function () {
        world.client = 'abc';
    });
};

step2.steps.js

var world = require('./test/features/support/world.js');

module.exports = function () {
    this.Then(/^some other step$/, function () {
        console.log(world.client);
    });
};