0

I have following code in Typescript:

export const commandsFactory = (options: CommandsOptions): CommandsFunctions => {
return {
waitForPageToLoad: (): void => {
  browser.waitUntil(
    () => {
      // console.log('Waiting for the page to load');
      return utils.checkIfPageLoaded();
    },
    {
      timeout: TIMEOUT_10000_MS,
      timeoutMsg: 'Page never completed loading'
    });
},
checkForJavaScriptErrors: (): void => {
  this.waitForPageToLoad(); // HERE I GET "TS2532: Object is possibly 'undefined'."
  let logs: any[] = browser.getLogs('browser');
  logs.forEach((log) => {
    if (log.level.toLowerCase() == 'severe') {
      if (log.source.toLowerCase() == 'javascript') {
        console.error(`${log.source.toUpperCase()} ERROR: ${log.message}`);
        expect.fail(`${log.source.toUpperCase()} ERROR: ${log.message}`);
      }
      else {
        console.log(`${log.source.toUpperCase()} ERROR: ${log.message}`);
      }
    }
  });
}
};
};

And I get an error for this keyword: TS2532: Object is possibly 'undefined'.
How can I call waitForPageToLoad() function from checkForJavaScriptErrors() function?
I feel this might be newbie question but I am not that familiar with the Typescript :)
Thanks!

mismas
  • 1,236
  • 5
  • 27
  • 55
  • Arrow functions deliberately change the behavior of `this`. Since you're trying to have `this` refer to the object returned on line two, you must use normal functions, not arrow functions. – Nicholas Tower Oct 16 '20 at 13:20
  • @mismas: With object literals you can also declare functions directly like this: `var o = { log() { console.log(this) } }`. The `this` will be the object itself, just like with `function` objects. – H.B. Oct 16 '20 at 13:30
  • @mismas thanks, but since this is a commonly asked question with a much more thorough answer in the linked post, the appropriate action would be to mark this as a duplicate. Plus, i don't need the internet points :) – Nicholas Tower Oct 16 '20 at 13:35

0 Answers0