Anil Pandey
Anil Pandey

Reputation: 11

Top level await in WebdriverIo Mocha tests

I am trying to use top-level await with WebdriverIO but keep getting below error

[0-0] import axios from 'axios'; [0-0] ^^^^^^ [0-0] [0-0] SyntaxError: Cannot use import statement outside a module [0-0] at Object.compileFunction (node:vm:352:18) [0-0] at wrapSafe (node:internal/modules/cjs/loader:1031:15) [0-0] at Module._compile (node:internal/modules/cjs/loader:1065:27) [0-0] at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) [0-0] at Module.load (node:internal/modules/cjs/loader:981:32) [0-0] at Function.Module._load (node:internal/modules/cjs/loader:822:12) [0-0] at ModuleWrap. (node:internal/modules/esm/translators:190:29) [0-0] at ModuleJob.run (node:internal/modules/esm/module_job:185:25) [0-0] at async Promise.all (index 0) [0-0] at async ESMLoader.import (node:internal/modules/esm/loader:281:24)

If I include "type": "module" in the package.json I get below error

ERROR @wdio/config:ConfigParser: Failed loading configuration file: /Users/anilp/custom-folder/experiments/wdio-mocha-sync/wdio.conf.js: require() of ES Module /Users/anilp/custom-folder/experiments/wdio-mocha-sync/wdio.conf.js from /Users/anilp/custom-folder/experiments/wdio-mocha-sync/node_modules/@wdio/config/build/lib/FileSystemPathService.js not supported. wdio.conf.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead rename wdio.conf.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /Users/anilp/custom-folder/experiments/wdio-mocha-sync/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

Framework: Mocha + WebdriverIO

import axios from 'axios';

// top-level await: Node >= v14.8.0 with ESM test file
const tests = await new Promise(async (resolve) => {
    const response = await axios.get("https://api.github.com/users", {
      headers: {
          Accept: "application/vnd.github.v3+json"
      }
  });
    resolve(response.data)
  });


describe('My Login application', () => {
    tests.forEach((d) => {
        it(`correctly print details of ${d.login} args`, function() {
          console.log(d);
        });
      });
});

Upvotes: 1

Views: 685

Answers (1)

Olga
Olga

Reputation: 95

I have been looking for the same thing and found this PR https://github.com/webdriverio/webdriverio/pull/6812. Looks like wdio doesn't have support for top-level await yet. May be in version 8..

Upvotes: 0

Related Questions