0

I am trying to build a custom logger and what I am trying to do as after I take a screenshot I want to call my logger function to log the image name. When I am in the then of the promise it cannot see all the functions in the class

module.exports = {
    takeScreenshot: function(driver, filename) {
        driver.takeScreenshot().then(function(data) {
          name = filename || 'ss.png';
          var screenshotPath = 'results/screenshots/';
          fs.writeFileSync(screenshotPath + name, data, 'base64');
          return screenshotPath + name;
        }).then(function(e) {
            this.logger(e, "true");
        });
    },

    logger: function(log, screenshot) {
      isScreenshot = screenshot || "false";
      var obj = {};
      if (isScreenshot == "true") {
        obj[testName.replace(/ /g,'')] = {
            logs: "",
            screenshot: "<img src=\"" +log+ "\" class=\"test-img\" />"
        };
        logger.push(obj);
      } else {
        obj[testName.replace(/ /g,'')] = {
            logs: "<span class=\"test-log\">" +log + "</span>",
            screenshot: ''
        };
        logger.push(obj);
      }
   }
}

Basically its not seeing the logger method. What am I missing? Thanks

jrock2004
  • 3,229
  • 5
  • 40
  • 73

2 Answers2

2

this is different in the context of the then callback. You'll need to create a closure in order for it to work.

Here is a great post on closures.

takeScreenshot: function(driver, filename) {
    var self = this;

    driver.takeScreenshot().then(function(data) {
      name = filename || 'ss.png';
      var screenshotPath = 'results/screenshots/';
      fs.writeFileSync(screenshotPath + name, data, 'base64');
      return screenshotPath + name;
    }).then(function(e) {
        self.logger(e, "true");
    });
},
Community
  • 1
  • 1
Hacknightly
  • 5,109
  • 1
  • 26
  • 27
0

Your this is different.
Read here for more info about this.

 takeScreenshot: function(driver, filename) {
        var self = this;
        driver.takeScreenshot().then(function(data) {
          name = filename || 'ss.png';
          var screenshotPath = 'results/screenshots/';
          fs.writeFileSync(screenshotPath + name, data, 'base64');
          return screenshotPath + name;
        }).then(function(e) {
            self.logger(e, "true");
        });
    },
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99