Невозможно прочитать свойство «on» неопределенного в новом JsonFormatter

Я пытаюсь создать отчет в формате html с помощью cucumber-html-reporter.

получение ошибки:

Unhandled rejection TypeError: Cannot read property 'on' of undefined
at new JsonFormatter (C:\path-to-project\node_modules\cucumber\src\formatter\json_formatter.js:21:5)
at Object.<anonymous> (C:\path-to-project\test\reporting\CucumberReportExtension.ts:43:27)

Проверены примечания к выпуску на наличие неопределённых параметров. Я не уверен, относится ли этот вопрос к этому! Если да, то может ли кто-нибудь помочь мне решить эту проблему.

Также, пожалуйста, дайте мне знать, если у вас есть лучшее решение для создания отчетов с помощью огуречного транспортира с использованием машинописного текста. (Пожалуйста, рассмотрите также приведенные ниже версии)

Версия транспортира: 5.1.2

Версия огурца: 3.0.0

ScenarioHook.ts

import {defineSupportCode} from "cucumber";
import {CucumberReportExtension} from 
"../reporting/CucumberReportExtension";

defineSupportCode(({AfterAll}) => {

  AfterAll(async () => {
     new CucumberReportExtension().myJsonFormatter;
  });
});

CucumberReportExtension.ts

import * as fs from 'fs';
import { mkdirp } from 'mkdirp';
import * as report from 'cucumber-html-reporter';
let Cucumber = require('cucumber');

export class CucumberReportExtension {

 private jsonDir = process.cwd() + "/reports/json";
 private htmlDir = process.cwd() + "/reports/html";
 private jsonFile = this.jsonDir + "/cucumber_report.json";

 private cucumberReporterOptions = {
    theme: "bootstrap",
    jsonFile: this.jsonFile,
    output: this.htmlDir + "/cucumber_reporter.html",
    reportSuiteAsScenarios: true,
    metadata: {
        "App Version":"0.0.1",
        "Test Environment": "TestingMicroSheet",
        "Browser": "Chrome  59.0.945",
        "Platform": "Windows 10",
        "Parallel": "Scenarios",
        "Executed": "Local"
    }
 };

 private CreateReportFile(dirName, fileName, fileContent) {
    //Check if the directory exist
    if (!fs.existsSync(dirName))
        mkdirp.sync(dirName);
    try {
        fs.writeFileSync(fileName, fileContent);
    }
    catch (message) {
        console.log("Failed to create File/Directory :" + message);
    }
 }

 private GenerateCucumberReport(cucumberReportOption){
    report.generate(cucumberReportOption);
 }

 myJsonFormatter = new Cucumber.JsonFormatter({
    log: jLog => {
        this.CreateReportFile(this.jsonDir, this.jsonFile, jLog);
        this.GenerateCucumberReport(this.cucumberReporterOptions);
    }
 });
}
export let JsonFormatter = new CucumberReportExtension().myJsonFormatter;

config.ts

import { Config } from 'protractor';

export let config: Config = {

 seleniumAddress: 'http://localhost:4444/wd/hub',

 framework: 'custom',
 frameworkPath: require.resolve('protractor-cucumber-framework'),
 specs: ["../features/*.feature"],

 baseUrl: "http://localhost:4200/",

 cucumberOpts: {
    compiler: "ts:ts-node/register",
    strict: true,
    format: ['json:../reporting/results.json'],
    require: ['../steps/*.js', '../hooks/*.js'],
    tags: '@smoke'
 }
}

package.json

{
  "name": "protractor-cucumber-sample",
  "version": "0.0.0",
  "private": true,
  "scripts": {
  "start": "node ./bin/www"
   },
  "dependencies": {
  "@types/jasmine": "^2.5.53",
  "body-parser": "~1.17.1",
  "cookie-parser": "~1.4.3",
  "debug": "~2.6.3",
  "express": "~4.15.2",
  "jade": "~1.11.0",
  "morgan": "~1.8.1",
  "serve-favicon": "~2.4.2"
   },
 "devDependencies": {
 "@types/chai": "^4.0.3",
 "@types/cucumber": "^2.0.3",
 "@types/mkdirp": "^0.5.0",
 "chai": "^4.1.1",
 "chai-as-promised": "^7.1.1",
 "cucumber": "^3.0.0",
 "cucumber-html-reporter": "^2.0.3",
 "jasmine": "^2.7.0",
 "jasminewd2": "^2.1.0",
 "protractor-cucumber-framework": "^4.0.2",
 "ts-node": "^3.3.0",
 "typescript": "^2.4.2"
  }
 }

Пожалуйста, дайте мне знать, если требуется дополнительная информация, которая поможет вам решить эту проблему.

Если это не тот форум, не могли бы вы ответить мне, указав правильную информацию о форуме, чтобы опубликовать эту проблему.

Заранее спасибо.


person Vinni    schedule 22.08.2017    source источник
comment
Это ошибка машинописи, я думаю, что в вашем проекте не установлены типы узлов! Также какую версию узла вы используете?   -  person Ram Pasala    schedule 22.08.2017
comment
Я использую Node версии v6.11.2. В приведенном выше сообщении об ошибке \node_modules\cucumber\src\formatter\json_formatter.js:21:5 речь идет о папке cucumber\src` folder. I have installed cucumber both locally and globally. I couldn't find src`.   -  person Vinni    schedule 22.08.2017
comment
Вместо этого я нашел options.eventBroadcaster.on('test-run-finished', _this.onTestRunFinished.bind(_this)); в cucumber\lib\formatter\json_formatter.json. Попытка пройти test-step-finished для eventBroadcaster в CucumberReportExtension.ts. Неудачно. Получение той же ошибки   -  person Vinni    schedule 22.08.2017
comment
это не имеет ничего общего с папкой src, вы не найдете ее при компиляции. Попробуйте установить типы узлов и проверьте, выходит ли ошибка - npm i -D @types/node   -  person Ram Pasala    schedule 22.08.2017
comment
Также вы должны указать свой @types в tsconfig.json. Пожалуйста, проверьте мой пример репозитория tsconfig.json   -  person Ram Pasala    schedule 22.08.2017
comment
Все еще сталкивается с той же проблемой. Я установил узел npm i -D @types/node. И мой tsconfig.json как { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "typeRoots": [ "./node_modules/@types" ], "types": ["node","cucumber"], "noImplicitAny": false, "strict": true, "lib": [ "es2015" ] } }   -  person Vinni    schedule 22.08.2017
comment
ваша цель должна быть es6, вот в чем проблема. огурец и транспортир последние используют функции es6   -  person Ram Pasala    schedule 22.08.2017
comment
Любая спецификация для lib? Я изменил target на es6. И протестировал его как с 2015, так и с 2016. Все еще сталкиваюсь с той же ошибкой   -  person Vinni    schedule 22.08.2017


Ответы (1)


С последней версией огурца 3.0 вы должны передать узел event emitter вашим пользовательским средствам форматирования. Для получения подробной информации о том, как работают события узла, перейдите по этой ссылке — https://nodejs.org/api/events.html

Теперь, чтобы использовать это в вашем CucumberReportExtension.ts

import * as fs from 'fs';
import { mkdirp } from 'mkdirp';
import * as report from 'cucumber-html-reporter';
let Cucumber = require('cucumber');
import { EventEmitter } from 'events';
const eventBroadcaster = new EventEmitter();

export class CucumberReportExtension {

private jsonDir = process.cwd() + "/reports/json";
private htmlDir = process.cwd() + "/reports/html";
private jsonFile = this.jsonDir + "/cucumber_report.json";

private cucumberReporterOptions = {
theme: "bootstrap",
jsonFile: this.jsonFile,
output: this.htmlDir + "/cucumber_reporter.html",
reportSuiteAsScenarios: true,
metadata: {
    "App Version":"0.0.1",
    "Test Environment": "TestingMicroSheet",
    "Browser": "Chrome  59.0.945",
    "Platform": "Windows 10",
    "Parallel": "Scenarios",
    "Executed": "Local"
  }
};

private CreateReportFile(dirName, fileName, fileContent) {
//Check if the directory exist
if (!fs.existsSync(dirName))
    mkdirp.sync(dirName);
try {
    fs.writeFileSync(fileName, fileContent);
}
catch (message) {
    console.log("Failed to create File/Directory :" + message);
 }
}

private GenerateCucumberReport(cucumberReportOption){
report.generate(cucumberReportOption);
 }

 myJsonFormatter = new Cucumber.JsonFormatter({
       eventBroadcaster: eventBroadcaster,
       log: jLog => {
           this.CreateReportFile(this.jsonDir, this.jsonFile, jLog);
           this.GenerateCucumberReport(this.cucumberReporterOptions);
        }
 });
}
export let JsonFormatter = new CucumberReportExtension().myJsonFormatter;

Примечание. Я еще не тестировал его, но он должен работать! Я обновлю ответ, как только закончу экспериментировать с новыми функциями огурца 3.0!

person Ram Pasala    schedule 22.08.2017