jadupl
jadupl

Reputation: 210

Webdriver.io - Node.js Unexpected token import - Page Object

Hello I have problem running my test scripts using Node.JS and Webdriver.io everything was working fine untill I tried to implement Page Object Pattern. On console output I receive error:

ERROR: Unexpected token import

user/Desktop/webdriverio-test/test/specs/first.js:2

import GooglePage from '../pom/GooglePage';

Node version: v8.9.1

GooglePage.js:

class GooglePage{

get submitButton(){ return browser.element(`[name="btnK"]`);}

get searchField(){return browser.element('#lst-ib');}

open(){
    browser.open("http://google.com");
}

submit(){
    this.submitButton.click();
}

setValue(text){
    this.searchField.setValue(text);
}
}
export default new GooglePage();

And test script:

var assert = require('assert');
import GooglePage from '../pom/GooglePage';
 
describe('Visiting Google by PageObjectPattern',()=>{
 it('Open Google',()=>{
     GooglePage.open();
     GooglePage.setValue("asdasd")
     })
  })   

Everything is almost the same as on: http://webdriver.io/guide/testrunner/pageobjects.html

Why it can't import my class to test script using import syntax?

Upvotes: 1

Views: 3142

Answers (1)

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

Couple of things to note:

1) Ensure that you are passing in the flag that enables ESM support in Node 8.5+

Enabling#

The --experimental-modules flag can be used to enable features for loading ESM modules.

Once this has been set, files ending with .mjs will be able to be loaded as ES Modules.

node --experimental-modules my-app.mjs

2) It appears that your ESM file's extension is ".js" and should instead be ".mjs", like so "GooglePage.mjs".

3) It also appears that you cannot import ESM from a CJS file and vs. So you'll either have to change your test spec to be a ".mjs" file, and import your dependencies like so:

import assert from 'assert';
import GooglePage from '../pom/GooglePage';

Or keep it as ".js" and require dependencies as CJS:

var assert = require('assert');
var GooglePage = require('../pom/GooglePage');

// Your module's content would be in GooglePage.default

Hope that helps!

Upvotes: 4

Related Questions