为什么黄瓜加载支持代码?

时间:2015-06-05 19:43:16

标签: javascript cucumber

我不得不说这可能是我曾经遇到的最疯狂的问题而我无法理解。我上课了;它被称为dashboard.js,它位于我的test/features/support文件夹中。这是内容:

'use strict';

class Dashboard {
  constructor(browser) {
    this.browser = browser;
  }

  viewGame(id) {
    return this.browser.get(`/dashboard/game/${id}`);
  }

  getTeamName(color) {
    return browser.findElement(By.model(`game.teams.${color}.name`)).getAttribute('value');
  }
}

module.exports = Dashboard;

我正在使用量角器进行黄瓜测试。我所有的测试都在另一台机器上运行得非常好,我没有改变它们,因为我把它们装在这台机器上。机器之间没有区别;两者都在完全相同的环境中运行完全相同版本的IOJS。

运行我的测试会给我这个错误。

[launcher] Error: TypeError: Class constructors cannot be invoked without 'new'
  at Object.Dashboard (c:\loluk\test\features\support\dashboard.js:4:14)
  at c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:62:25
  at Array.forEach (native)
  at Object.wrapper (c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:59:15)
  at Object.initializer (c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:20:37)

从我的测试代码中删除require到此支持文件并不能解决问题;黄瓜仍然加载它。我没有配置告诉它加载任何支持文件。因此,我自然会将文件夹从support更改为lib。这应该解决问题 - 对吧?毕竟,它不是命名支持。

[launcher] Error: TypeError: Class constructors cannot be invoked without 'new'
  at Object.Dashboard (c:\loluk\test\features\lib\dashboard.js:4:14)
  at c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:63:25
  at Array.forEach (native)
  at Object.wrapper (c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:60:15)
  at Object.initializer (c:\loluk\node_modules\cucumber\lib\cucumber\cli\support_code_loader.js:21:41)
  at Object.Library (c:\loluk\node_modules\cucumber\lib\cucumber\support_cod

不。事实上,无论我重命名这个文件,还是它的文件夹,它都会自动加载,尽管我从不告诉Cucumber这样做。更奇怪的是,Cucumber不仅加载它,而且还试图通过某种原因调用它。这意味着无论出于什么原因它正在尝试执行我的类 - 它没有在另一台机器上执行它。

有谁知道我怎么能说服这种红润的黄瓜表现出来?只有移动features文件夹中的文件OUT才能解决此问题,但我不明白为什么要加载代码

  • 我没有要求
  • 它没有在另一台电脑上播放
  • 它不应该加载,因为它在步骤定义文件夹
  • 之外

1 个答案:

答案 0 :(得分:1)

你需要了解两件事。首先是:

$ cucumber.js --help提取:

-r, --require LIBRARY|DIR     Require files before executing the features. If
                              this option is not specified, all *.js and
                              *.coffee files that are siblings or below the
                              features will be loaded automatically. Automatic
                              loading is disabled when this option is specified,
                              and all loading becomes explicit.

                              Files under directories named "support" are
                              always loaded first.

第二件事是:当Cucumber 为您加载文件时,它将检查该文件导出的内容是否为函数。如果是,它将自动执行。这允许在简单函数(module.exports = function () { this.Given(...) })中声明步骤定义。如果你的某个文件导出了一个类构造函数,那么它也会被Cucumber执行(没有new关键字),这会导致潜在的问题。

最简单的解决方法是将该类导出为exports的属性,如下所示:

module.exports.Dashboard = class ...

显然,您需要稍微更改一下require语句:

var Dashboard = require('./path/to/dashboard.js').Dashboard;

解决问题的另一种方法是在CLI中明确使用--require标志,如帮助中所述。

相关问题