无法读取未定义的 属性 'JsonFormatter'

Cannot read property 'JsonFormatter' of undefined

随着 Cucumberjs2.3.0 的推出,我不得不对 hooks.js 文件进行一些更改,以便让 cucumber-html-reporter 再次工作。

hooks.js 显式地创建了一个包含执行报告的 json 文件,稍后我将使用它来生成 HTML 报告(因为我同时需要 JSON 和小黄瓜输出)。

这里是 hooks.js,Cucumberjs2.3.0 有一些更新:

var JsonFormatter = require('cucumber').JsonFormatter;
var fs = require('fs');
var reporter = require('cucumber-html-reporter');
var CucumberHtmlReport = require('cucumber-html-report');
var seleniumWebdriver = require('selenium-webdriver');
var {defineSupportCode} = require('cucumber');

'use strict';

defineSupportCode(function({After,registerHandler,registerListener}) {

    var outputDir = './'

    After(function (scenario,callback) {
        if (scenario.isFailed()) {
            browser.takeScreenshot().then(function (base64png) {
                 scenario.attach(new Buffer(base64png, 'base64'), 'image/png');
                 callback();
            }, function (err) {
                return callback(err);
            });
        } else{
            callback();
        }
    });

    var createHtmlReport = function (sourceJson) {
        var report = new CucumberHtmlReport({
            source: sourceJson
            , dest: outputDir
        });
        report.createReport();
    };

    //I don't know what method to call since now JsonFormatter is a class!
    var JsonFormatter = Cucumber.Listener.JsonFormatter();
    JsonFormatter.log = function (string) {
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir);
        }

        var targetJson = outputDir + 'cucumber.json';
        fs.writeFile(targetJson, string, function (err) {
            if (err) {
                console.log('Failed to save cucumber test results to json file.');
                console.log(err);
            } else {
                createHtmlReport(targetJson);
            }
        });
    };

   registerListener(JsonFormatter);
});

我注意到 Cucumberjs2.3.0 不再有包含 JsonFormatter 的监听器 class。这让我想到了我的问题,我不知道如何调用该方法来创建 JSON 文件,该文件位于 hooks.js:

的这一行中
var JsonFormatter = Cucumber.Listener.JsonFormatter(); ///?????

当我 运行 我的测试我得到这个错误:

Unhandled rejection TypeError: Cannot read property 'JsonFormatter' of undefined
    at C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\support\hooks.js:36:39
    at C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\cucumber\lib\support_code_library\builder.js:77:12
    at Array.forEach (native)
    at Object.build (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\cucumber\lib\support_code_library\builder.js:76:7)
    at Cli.getSupportCodeLibrary (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\cucumber\lib\cli\index.js:137:32)
    at Cli.<anonymous> (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\cucumber\lib\cli\index.js:144:39)
    at Generator.next (<anonymous>)
    at Generator.tryCatcher (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\util.js:16:23)
    at PromiseSpawn._promiseFulfilled (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\generators.js:97:49)
    at Promise._settlePromise (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\promise.js:574:26)
    at Promise._settlePromise0 (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\promise.js:693:18)
    at Async._drainQueue (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (C:\workspace\TestFinalMile\trunk\src\test\resources\integration\finalmile\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:649:20)

[11:06:33] E/launcher - BUG: launcher exited with 1 tasks remaining
npm ERR! Test failed.  See above for more details.

我的 hooks.js 需要更改什么才能使其在 5 月 12 日 Cucumberjs2.3.0 出现之前正常工作?

这是我的量角器配置文件,以防万一:

var featsLocation = 'features/';
var stepsLocation = 'steps/';

exports.config = {
    directConnect: true,
    chromeDriver: '/srv/build/applications/chromedriver/chromedriver.exe',
    seleniumServerJar: '/srv/build/applications/selenium/selenium-server-standalone-3.4.0.jar',
    rootElement: 'html',
    params:{
        authURL: '',    
        login:{
            email:'',
            passw:''
        }
    },
    resultJsonOutputFile:'',
    getPageTimeout: 30000,
    allScriptsTimeout: 30000,
    framework: 'custom',
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'chrome',
            chromeOptions:{
                args:[]//"--headless"]
            }
        //'browserName': 'phantomjs',
        //'phantomjs.binary.path': '/srv/build/applications/phantomjs/bin/phantomjs'   //<--Comment to run from local
    },

    onPrepare: function(){
        global.EC = protractor.ExpectedConditions;
    },

    specs: [ /**/
              featsLocation+'authenticateCSM.feature'
            , featsLocation+'rejects.feature'
            , featsLocation+'rejects_sprint.feature'
     ],

     baseUrl: '',

     cucumberOpts: {
         tags: '',
         require: [
                   './support/*.js'
                    , stepsLocation+'*.spec.js'

        ],
        monochrome: true,
        strict: true,
        plugin: "json"
     },
};

这也是我的 package.json:

{
  "name": "CucumberjsAT",
  "version": "1.0.0",
  "description": "Executes automated test, using Cucumberjs",
  "scripts": {
    "test": "protractor ./protractorConf.js --params.authURL=\"http://myweb.com\" --params.login.email=user@mail.com --params.login.passw=password --cucumberOpts.tags \"not @ignore and (@smoke or @me)\""
  },
  "author": "Kyon"
}

这是我的框架信息,希望对您有所帮助...

我找到了问题的解决方案。

通过在包上传递参数向 json 文件提供名称。然后下面更改hooks.js.

中的After场景
After(function (scenario,callback) {
    let self = this;
    if (scenario.isFailed()) {
        browser.takeScreenshot().then(function (base64png) {
             self.attach(new Buffer(base64png, 'base64'), 'image/png');
             callback();
        }, function (err) {
            return callback(err);
        });
    } else{
        callback();
    }
});