javascriptjwtmocha.jswebdriver-iowdio-v6

WebdiverIO wdio config: using a variable


In the wdio.conf.js file, I'm using the beforeTest section to set a JSON web token so that, later on in the test suites I no longer need to login into the web application.

If the token is hardcode, this action is working perfectly! Yet I would like to create a variable 'jwt' and assign it the value of the JSON web token. When I do this, an error is given "jwt is not defined".

At the top of wdio.conf.js I write the following code const jwt = 'eyJ0eXAiOiJKV1QiLCJhb...'

In the before action I write the following code

   console.log('before exe ' + jwt)
   browser.execute(() => localStorage.setItem('usertoken', jwt))
   console.log('after exe ' + jwt)

The console log's are showing the token, so the variable is working inside of the beforeTesting action. Yet I'm getting the error '[0-0] Error in "BeforeTest Hook" javascript error: jwt is not defined'


Solution

  • The browser doesn't know the jwt variable. You should pass this value as the argument of the function as stated in the docs: https://webdriver.io/docs/api/browser/execute.html.

    browser.execute((browser_jwt) => localStorage.setItem('usertoken', browser_jwt), jwt)