0

I declared a property in class constructor and accessing through methods, which is declared as 'static', with 'this' and it is not accessible. How to get access to constructor (class) variables inside static methods?

export class Reporter {
    constructor() {
        this.jsonReports = path.join(process.cwd(), "/reports/json")

        this.cucumberReporterOptions = {
            jsonFile: targetJson,
            output: htmlReports + "/cucumber_reporter.html",
            reportSuiteAsScenarios: true,
            theme: "bootstrap",
        }
    }

    static createHTMLReport() {
        try {
            reporter.generate(this.cucumberReporterOptions);
        } catch (err) {

        }
    }
}

Updated:

As per "@CodingIntrigue", I have done like this in 'reporter.js' file and called the method as Reporter.createHTMLReport() in my config file and its working as expected. But not sure if this is best practice.

const jsonReports = path.join(process.cwd(), "/reports/json")

const cucumberReporterOptions = {
    jsonFile: targetJson,
    output: htmlReports + "/cucumber_reporter.html",
    reportSuiteAsScenarios: true,
    theme: "bootstrap",
}

export class Reporter {
    static createHTMLReport() {
        try {
            reporter.generate(cucumberReporterOptions);
        } catch (err) {

        }
    }
}
mmar
  • 1,840
  • 6
  • 28
  • 41

1 Answers1

1

If you want to continue using class syntax, you can just make jsonReports and cucubmerReporterOptions static properties too:

export class Reporter {
    static createHTMLReport() {
        try {
            reporter.generate(Reporter.cucumberReporterOptions);
        } catch (err) {

        }
    }
}

Reporter.jsonReports = path.join(process.cwd(), "/reports/json")

Reporter.cucumberReporterOptions = {
    jsonFile: targetJson,
    output: htmlReports + "/cucumber_reporter.html",
    reportSuiteAsScenarios: true,
    theme: "bootstrap",
}
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • I have updated the question with the solution I have done as per your suggestion and its working too. But not sure if this could be a good practice to follow. – mmar May 25 '18 at 13:05
  • That practice is fine. You should post your code in an answer – CodingIntrigue May 25 '18 at 13:06
  • @CodingIntrigue Using a `class` without a constructor, without instance properties, without any instance methods, is *not* a "fine practice". – Bergi May 25 '18 at 13:19
  • 1
    @Bergi I did say in the comments above that it shouldn't be a `class` at all, but I was going on the possibly incorrect assumption that not *everything* was going to be static in the class – CodingIntrigue May 25 '18 at 13:24