Git Product home page Git Product logo

selenium-cucumber-js's Introduction

selenium-cucumber-js

npm

JavaScript browser automation framework using official selenium-webdriver and cucumber-js.

If you prefer to work with puppeteer check out puppeteer-cucumber-js

Table of Contents

Installation

npm install selenium-cucumber-js --save-dev

Usage

node ./node_modules/selenium-cucumber-js/index.js -s ./step-definitions

Options

-h, --help                          output usage information
-V, --version                       output the version number
-s, --steps <path>                  path to step definitions. defaults to ./step-definitions
-p, --pageObjects <path>            path to page objects. defaults to ./page-objects
-o, --sharedObjects [paths]         path to shared objects (repeatable). defaults to ./shared-objects
-b, --browser <path>                name of browser to use. defaults to chrome
-k, --browser-teardown <optional>   browser teardown strategy after every scenario (always, clear, none). defaults to "always"
-r, --reports <path>                output path to save reports. defaults to ./reports
-d, --disableLaunchReport           disable the auto opening the browser with test report
-j, --junit <path>                  output path to save junit-report.xml defaults to ./reports
-t, --tags <tagName>                name of tag to run
-f, --featureFile <path>            a specific feature file to run
-x, --timeOut <n>                   steps definition timeout in milliseconds. defaults to 10 seconds
-n, --noScreenshot                  disable auto capturing of screenshots when an error is encountered

By default tests are run using Google Chrome, to run tests using another browser supply the name of that browser along with the -b switch. Available options are:

Browser Example
Chrome -b chrome
Firefox -b firefox
Phantom JS -b phantomjs
Electron -b electron
Custom -b customDriver.js

To use your own driver, create a customDriver.js file in the root of your project and provide the filename with the -b switch.

Configuration file

Configuration options can be set using a selenium-cucumber-js.json file at the root of your project. The JSON keys use the "long name" from the command line options. For example the following duplicates default configuration:

{
    "steps": "./step-definitions",
    "pageObjects": "./page-objects",
    "sharedObjects": "./shared-objects",
    "reports": "./reports",
    "browser": "chrome",
    "timeout": 10000
}

Whereas the following would set configuration to match the expected directory structure of IntelliJ's Cucumber plugin, and make default timeout one minute. Note that the default browser has not been overridden and will remain 'chrome'.

{
    "steps": "./features/step_definitions",
    "pageObjects": "./features/page_objects",
    "sharedObjects": "./features/shared_objects",
    "reports": "./features/reports",
    "timeout": 60000
}

Feature files

A feature file is a Business Readable, Domain Specific Language file that lets you describe software’s behavior without detailing how that behavior is implemented. Feature files are written using the Gherkin syntax and must live in a folder named features within the root of your project.

# ./features/google-search.feature

Feature: Searching for vote cards app
  As an internet user
  In order to find out more about the itunes vote cards app
  I want to be able to search for information about the itunes vote cards app

  Scenario: Google search for vote cards app
    When I search Google for "itunes vote cards app"
    Then I should see some results

Browser teardown strategy

The browser automatically closes after each scenario to ensure the next scenario uses a fresh browser environment. But you can change this behavior with the "-k" or the "--browser-teardown" parameter.

Value Description
always the browser automatically closes (default)
clear the browser automatically clears cookies, local and session storages
none the browser does nothing

Step definitions

Step definitions act as the glue between features files and the actual system under test.

To avoid confusion always return a JavaScript promise your step definition in order to let cucumber know when your task has completed.

// ./step-definitions/google-search-steps.js

module.exports = function () {

    this.Then(/^I should see some results$/, function () {

        // driver wait returns a promise so return that
        return driver.wait(until.elementsLocated(by.css('div.g')), 10000).then(function(){

            // return the promise of an element to the following then.
            return driver.findElements(by.css('div.g'));
        })
        .then(function (elements) {

            // verify this element has children
            expect(elements.length).to.not.equal(0);
        });
    });
};

The following variables are available within the Given(), When() and Then() functions:

Variable Description
driver an instance of selenium web driver (the browser)
selenium the raw selenium-webdriver module, providing access to static properties/methods
page collection of page objects loaded from disk and keyed by filename
shared collection of shared objects loaded from disk and keyed by filename
helpers a collection of helper methods things selenium does not provide but really should!
by the selenium By class used to locate elements on the page
until the selenium until class used to wait for elements/events
expect instance of chai expect to expect('something').to.equal('something')
assert instance of chai assert to assert.isOk('everything', 'everything is ok')
trace handy trace method to log console output with increased visibility

Page objects

Page objects are accessible via a global page object and are automatically loaded from ./page-objects (or the path specified using the -p switch). Page objects are exposed via a camel-cased version of their filename, for example ./page-objects/google-search.js becomes page.googleSearch. You can also use subdirectories, for example ./page-objects/dir/google-search.js becomes page.dir.googleSearch.

Page objects also have access to the same runtime variables available to step definitions.

An example page object:

// ./page-objects/google-search.js

module.exports = {

    url: 'http://www.google.co.uk',

    elements: {
        searchInput: by.name('q'),
        searchResultLink: by.css('div.g > h3 > a')
    },

    /**
     * enters a search term into Google's search box and presses enter
     * @param {string} searchQuery
     * @returns {Promise} a promise to enter the search values
     */
    performSearch: function (searchQuery) {

        var selector = page.googleSearch.elements.searchInput;

        // return a promise so the calling function knows the task has completed
        return driver.findElement(selector).sendKeys(searchQuery, selenium.Key.ENTER);
    }
};

And its usage within a step definition:

// ./step-definitions/google-search-steps.js
this.When(/^I search Google for "([^"]*)"$/, function (searchQuery) {

    return helpers.loadPage('http://www.google.com').then(function() {

        // use a method on the page object which also returns a promise
        return page.googleSearch.performSearch(searchQuery);
    })
});

Shared objects

Shared objects allow you to share anything from test data to helper methods throughout your project via a global shared object. Shared objects are automatically loaded from ./shared-objects (or the path specified using the -o switch) and made available via a camel-cased version of their filename, for example ./shared-objects/test-data.js becomes shared.testData. You can also use subdirectories, for example ./shared-objects/dir/test-data.js becomes shared.dir.testData.

Shared objects also have access to the same runtime variables available to step definitions.

An example shared object:

// ./shared-objects/test-data.js

module.exports = {
    username: "import-test-user",
    password: "import-test-pa**word"
}

And its usage within a step definition:

module.exports = function () {

    this.Given(/^I am logged in"$/, function () {

        driver.findElement(by.name('usn')).sendKeys(shared.testData.username);
        driver.findElement(by.name('pass')).sendKeys(shared.testData.password);
    });
};

Helpers

selenium-cucumber-js contains a few helper methods to make working with selenium a bit easier, those methods are:

// Load a URL, returning only when the <body> tag is present
helpers.loadPage('http://www.google.com');

// get the value of a HTML attribute
helpers.getAttributeValue('body', 'class');

// get a list of elements matching a query selector who's inner text matches param.
helpers.getElementsContainingText('nav[role="navigation"] ul li a', 'Safety Boots');

// get first elements matching a query selector who's inner text matches textToMatch param
helpers.getFirstElementContainingText('nav[role="navigation"] ul li a', 'Safety Boots');

// click element(s) that are not visible (useful in situations where a menu needs a hover before a child link appears)
helpers.clickHiddenElement('nav[role="navigation"] ul li a','Safety Boots');

// wait until a HTML attribute equals a particular value
helpers.waitUntilAttributeEquals('html', 'data-busy', 'false', 5000);

// wait until a HTML attribute exists
helpers.waitUntilAttributeExists('html', 'data-busy', 5000);

// wait until a HTML attribute no longer exists
helpers.waitUntilAttributeDoesNotExists('html', 'data-busy', 5000);

// get the content value of a :before pseudo element
helpers.getPseudoElementBeforeValue('body header');

// get the content value of a :after pseudo element
helpers.getPseudoElementAfterValue('body header');

// clear the cookies
helpers.clearCookies();

// clear both local and session storages
helpers.clearStorages();

// clear both cookies and storages
helpers.clearCookiesAndStorages('body header');

// waits until an element to exist and returns it
helpers.waitForCssXpathElement('#login-button', 5000);

// scroll until element is visible
helpers.scrollToElement(webElement);

// select a value inside a dropdown list by its text
helpers.selectByVisibleText('#country', 'Brazil');

// waits and returns an array of all windows opened
helpers.waitForNewWindows();

Visual Comparison

The selenium-cucumber-js framework uses Applitools Eyes to add visual checkpoints to your JavaScript Selenium tests. It takes care of getting screenshots of your application from the underlying WebDriver, sending them to the Applitools Eyes server for validation and failing the test when differences are detected. To perform visual comparisons within your tests, obtain an Applitools Eyes API Key and assign it to the eye_key property of the selenium-cucumber-js.json config file in the root of your project.

For example the following configuration could be used with an increased timeout which allows enough time for visual checks:

{
  "eye_key": "Your_Api_Key",
  "timeout": 50000
}

And its usage within page Objects:

module.exports = {

    url: 'https://applitools.com/helloworld',

    elements: {
        clickme: by.tagName('button'),
        searchResultLink: by.css('div.g > h3 > a')
    },

    applitools_Eyes_Example: function () {

        // Start the test and set the browser's viewport size to 800x600.
        eyes.open(driver, 'Hello World!', 'My first Javascript test!',
            {width: 800, height: 600});

        // Navigate the browser to the "hello world!" web-site.
        driver.get(page.HelloWorld.elements.url);

        // Visual checkpoint #1.
        eyes.checkWindow('Main Page');

        // Click the "Click me!" button.
        driver.findElement(page.HelloWorld.elements.clickme).click();

        // Visual checkpoint #2.
        eyes.checkWindow('Click!');

        // End the test.
        eyes.close();
    }
};

Before/After hooks

You can register before and after handlers for features and scenarios:

Event Example
BeforeFeature this.BeforeFeatures(function(feature, callback) {})
AfterFeature this.AfterFeature(function(feature, callback) {});
BeforeScenario this.BeforeScenario(function(scenario, callback) {});
AfterScenario this.AfterScenario(function(scenario, callback) {});
module.exports = function () {

    // add a before feature hook
    this.BeforeFeature(function(feature, done) {
        console.log('BeforeFeature: ' + feature.getName());
        done();
    });

    // add an after feature hook
    this.AfterFeature(function(feature, done) {
        console.log('AfterFeature: ' + feature.getName());
        done();
    });

    // add before scenario hook
    this.BeforeScenario(function(scenario, done) {
        console.log('BeforeScenario: ' + scenario.getName());
        done();
    });

    // add after scenario hook
    this.AfterScenario(function(scenario, done) {
        console.log('AfterScenario: ' + scenario.getName());
        done();
    });
};

Reports

HTML and JSON reports are automatically generated and stored in the default ./reports folder. This location can be changed by providing a new path using the -r command line switch:

Cucumber HTML report

How to debug

Most selenium methods return a JavaScript Promise that is resolved when the method completes. The easiest way to step in with a debugger is to add a .then method to a selenium function and place a debugger statement within it, for example:

module.exports = function () {

    this.When(/^I search Google for "([^"]*)"$/, function (searchQuery, done) {

        driver.findElement(by.name('q')).then(function(input) {
            expect(input).to.exist;
            debugger; // <<- your IDE should step in at this point, with the browser open
            return input;
        })
        .then(function(input){
            input.sendKeys(searchQuery);
            input.sendKeys(selenium.Key.ENTER);

            done(); // <<- let cucumber know you're done
        });
    });
};

Directory structure

You can use the framework without any command line arguments if your application uses the following folder structure:

.
├── features
│   └── google-search.feature
├── step-definitions
│   └── google-search-steps.js
├── page-objects
│   └── google-search.js
└── shared-objects
│   ├── test-data.js
│   └── stuff.json
└── reports
    ├── cucumber-report.json
    └── cucumber-report.html

Demo

This project includes an example to help you get started. You can run the example using the following command:

node ./node_modules/selenium-cucumber-js/index.js

Bugs

Please raise bugs via the selenium-cucumber-js issue tracker and, if possible, please provide enough information to allow the bug to be reproduced.

Contributing

Everyone is very welcome to contribute to this project. You can contribute just by submitting bugs or suggesting improvements by opening an issue on GitHub.

Troubleshooting

IntelliJ Cucumber Plugin

IntelliJ based IDE's have a plugin that allows the tester to control click on a Given, When, Then statement within a Cucumber feature file and have the user taken to the associated step definition. This plugin relies on your project having the following folder structure:

.
└── features
   │   google-search.feature
   └── step_definitions
   │   └── google-search-steps.js
   └── page_objects
   │   └── google-search.js
   └── shared_objects
   │   ├── test-data.js
   │   └── stuff.json
   └── reports
       ├── cucumber-report.json
       └── cucumber-report.html

This can be achieved by restructuring your project to match the layout above (notice the underscores), and running your tests with the following switches:

node ./node_modules/selenium-cucumber-js/index.js -s ./features/step_definitions -p ./features/page_objects -o ./features/shared_objects -r ./features/reports

VSCode Cucumber Plugin

Visual Studio Code has also an extension for Cucumber (Gherkin) Language Support + Format + Steps/PageObjects Autocomplete. You can find how to install and use at Cucumber (Gherkin) Full Support.

Following the default structure, the settings.json should look like this:

{
    "cucumberautocomplete.steps": [
        "step-definitions/*.js"
    ],
    "cucumberautocomplete.syncfeatures": "features/*.feature",
    "cucumberautocomplete.strictGherkinCompletion": false,
    "cucumberautocomplete.onTypeFormat": true,
    "editor.quickSuggestions": {
        "comments": false,
        "strings": true,
        "other": true
    },
    "cucumberautocomplete.gherkinDefinitionPart": "(Given|When|Then)\\(",
}

License

Licensed under ISC License © John Doherty

selenium-cucumber-js's People

Contributors

aashwin avatar afuca avatar bkarolyi avatar bricas avatar brigantian-nttdata avatar d4niloarantes avatar danyg avatar dependabot[bot] avatar f2acode avatar george1410 avatar itmayziii avatar jogonzal avatar john-doherty avatar kbytesys avatar khause avatar leggebroten avatar mivtachyahu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

selenium-cucumber-js's Issues

CLI option for localization

Hello. How can I change global language for features?
In cucumber-js I can use cli options --language but in selenium-cucumber-js I use # language: ru at first line of feature for every feature

Having two features fail to run

I have a two features and if i do run

node ./node_modules/selenium-cucumber-js/index.js

I get
node_modules/selenium-cucumber-js/runtime/world.js:177 The previously configured ChromeDriver service is still running. You must shut it down before you may adjust its configuration.

Expected
One test ends another start

Phantonjs doesn't work correct with Ajax

When I run tests using Phantomjs - ajax is pending.
such settings
'phantomjs.cli.args': ['--web-security=false', '--ignore-ssl-errors=true', '--webdriver-loglevel=DEBUG'],
could help to resolve this issue

Added CLI init helper

Adding selenium-cucumber-js to a project is a bit of a hassle as you have to create the dependant folders. It would be far cleaner to execute two commands and have the framework up and running. For example

# install the framework
npm install --save-dev selenium-cucumber-js

# create folders and insert google example
node ./node_modules/selenium-cucumber-js/index init

How to use the before/after hooks?

I have read the readme file, but I do not understand where those should be located.
lets take an example, I want to print the name of the feature before each feature.

// before-hook.js
module.exports = function () {
    // add a before feature hook
    this.BeforeFeature(function(feature, done) {
        console.log('BeforeFeature: ' + feature.getName());
        done();
    });
};
  1. that means this code will run before each feature?
  2. what is done?
  3. where should before-hooks.js should be located? (features folder? else?

Thanks!

How do i execute a single specific .feature file using selenium-cucumber-js

Currently to run my automation tests i am using *node index.js -s .\step-definitions -r .\reports*
to run a specific feature i need to add a tag and then use it in above command with a -t arg

but i have existing set of feature files where I donot have proper tags, is there some way we can specify a single .feature file in the above command to execute the tests as we can do with cucumber-js
eg : providing : .\features\login.feature

hook for creating a driver

Hi,

Love the wrapper. Thank you for it.

What I need is to be able to control the driver configuration (browsers, resolutions, and local, versus remote).
Do you have or plan to have a hook or configuration option for driver construction?

-Lee

Before/After handlers

Hi,

I've not been able to get the Before/After Feature or Scenario event handlers working in my step definitions.

    this.BeforeFeature(/^Feature Name$/, function () {
        return helpers.loadPage('http://localhost/login').then(function() {
            return page.login.login(shared.testData.username, shared.testData.password);
        });
    });

Is there an example of how to do this? The above code works in a When - is something like this possible in a Before/After?

Thanks!

On Hooks the "driver" object is null

Hello friends,

I'm trying to load a page and perform a login action under a Hook before run the actual feature so I can login multiple users from the Hook based on Tags. Since multiple backgrounds are not allowed on features by cucumber, I was thinking on this solution.

when trying to implement it, I'm trying to load a url using the helper or directly using driver.get ,however, it fires an error:
TypeError: node_modules/selenium-cucumber-js/node_modules/cucumber/lib/cucumber/support_code/library.js:17 Cannot read property 'get' of null

Anybody has any idea about how to fix this?

My Hook code is:
/* * Adds a before feature hook */ this.BeforeFeature(function(feature, done) { feature.getTags().forEach(function (tag) { // Only features for Client Access if(tag.getName() === '@user-01') { // load the url and wait for it to complete driver.get("https://google.com/").then(function() { // now wait for the body element to be present return driver.wait(until.elementLocated(by.css('body')), 10000); }); } }); done(); });

how to use attach inside of a step

Looking to use the "attach" to include a screenshot of a particular step. This is outlined in cucumber-js as seen by this code:

Given(/^a basic step$/, function() {
  this.attach('Some info.')
  this.attach('{"some", "JSON"}}', 'application/json')
})

from:
https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/attachments.md

error is:
this.attach is not a function

At first I thought it was because I was using an arrow function (per the cucumber notes this doesn't work because of rebinding), but I switched to a regular function and still no luck.

Thanks!

Error with execution after just updating cucumber to latest version(4.2.1)

Hi,

I tried to run this project with just updating cucumber version to latest(4.2.1).
But I've caught an error below:

My-MAC:selenium-cucumber-js fbb$node index.js
/Users/fbb/Frameworks/cucumber-test8/selenium-cucumber-js/node_modules/babel-runtime/helpers/classCallCheck.js:7
throw new TypeError("Cannot call a class as a function");
^

TypeError: Cannot call a class as a function
at exports.default (/Users/fbb/Frameworks/cucumber-test8/selenium-cucumber-js/node_modules/babel-runtime/helpers/classCallCheck.js:7:11)
at Object.Cli (/Users/fbb/Frameworks/cucumber-test8/selenium-cucumber-js/node_modules/cucumber/lib/cli/index.js:78:34)
at Object. (/Users/fbb/Frameworks/cucumber-test8/selenium-cucumber-js/index.js:128:28)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

Kindly let me know what am I doing wrong here.

AfterScenario detect if scenario failed or no

Hello friends,

anybody knows how to detect on the hook AfterScenario if it failed or no?

I tried already with: IsFailed
if (!scenario.isFailed) { driver.call(setScore, null, 'pass').then(function(result){ console.log('set score to pass'); }); } done();

I had no cluck with that.

Any idea is always welcome.

New version does not install all dependencies

After npm install I got

node ./node_modules/selenium-cucumber-js/index.js
module.js:472
    throw err;
    ^

Error: Cannot find module 'eyes.selenium'

I installed eyes.selenium using

npm install eyes.selenium --save

Weirdly it eyes.selenium is listed as a dependency in this project.

Edited:
Oh it's listed in dev dependencies

Cucumber 2.x

Jus a question and not a bug per se, but, are there any plans to support Cucumber.js 2.x?

page.mammothWorkwear undefined in buy-workwear-steps.js

return helpers.loadPage(page.mammothWorkwear.url);

gettting

TypeError: Cannot read property 'url' of undefined at createWorld.<anonymous> (/Users/rhowk1271/Sites/time/_style/instyle/be-fe-instyle/features/step_definitions/buy-workwear-steps.js:6:53) at _combinedTickCallback (internal/process/next_tick.js:95:7) at process._tickCallback (internal/process/next_tick.js:161:9) at Function.Module.runMain (module.js:607:11) at startup (bootstrap_node.js:158:16)
when I run the example using the directory structure cited at the end of the readme, and the command:
node ./node_modules/selenium-cucumber-js/index.js -s ./features/step_definitions -p ./features/page_objects -o ./features/shared_objects -r ./features/reports
Thanks in advance for any help!

Parallel Execution

Hi,

Is there anyway that we can improve this framework to execute the scenarios in parallel?

Cannot run tests

I have Windows 7 and after I cloned application and run npm install and then node index.js I got following error
selenium-cucumber-js\node_modules\selenium-web
driver\index.js:115
static createSession(...args) {}
^^^

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (C:\Users\Vera\Desktop\SlotMachine\selenium-cucumber-j
s\runtime\world.js:13:16)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)

timeOut option no longer respected?

Running my test suite from the command-line, I specify "-x 20000", but since version 1.4.9 I've seen this error:

function timed out after 10000 milliseconds

I'm sure it had worked prior.

Add screenshot/comment into test report

Hi,
I am new with selenium-cucumber-js, I would like to add custom message and screenshot to the html report, but I dont know how.

I am not sure if the FW also support this, if not please consider to support this. Otherwise, appreciate if you can give me an example.

Helper getElementsContainingText trim

What about removing whitespaces from both sides of strings in the condition of 'getElementsContainingText' helper ?

By changing it with something like this:

if (elements[i][txtProp].trim() === content.trim()) {
    results.push(elements[i]);
}

The problem I encounter is that HTML tags had not the same innerText and textContent string values and both could contained (not the same) leading and trailing whitespace(s) and carriage return(s).

So, If I want to search "Hello" in these examples, currently only the first will work all the time:

<span>Hello</span>

<span> Hello  </span>

<span>
    Hello
</span>

As a workaround, I copy-paste the getElementsContainingText content function in my test code with the fix above.

selenium-cucumber-js.json configuration file is not being merged

Hi,
I'm using a selenium-cucumber-js.json file at the root of my project with these options:
{
"steps": "./features/step-definitions",
"pageObjects": "./page-objects",
"sharedObjects": "./shared-objects",
"reports": "./reports",
"browser": "firefox",
"timeout": 100000
}
but when I run the tests (>node ./node_modules/selenium-cucumber-js/index.js), the options used are the ones on index file:
{
"steps": "./step-definitions",
"pageObjects": "./page-objects",
"sharedObjects": "./shared-objects",
"reports": "./reports",
"browser": "chrome",
"timeout": 10000
}

Am I doing anything wrong? Or there is a problem on index.js when reading the file?

var configFileName = path.resolve(process.cwd(), 'selenium-cucumber-js.json');
if (fs.isFileSync(configFileName)) {
config = Object.assign(config, require(configFileName));
}

Thanks,
Vitor Carvalho

Unable to initiate tests on edge

I am unable to trigger the scripts on Microsoft EDGE.

Added following settings in world.js
case 'edge': {
console.log('in world edge');
driver = new selenium.Builder().withCapabilities({
browserName: 'microsoftedge',
javascriptEnabled: true,
acceptSslCerts: true,
path: "path to microsoftWebdriver.exe"
}).build();
} break;

getting error : do not know to initiate microsoftedge.

Custom driver configurations

How do I set custom web driver instances ? Do I need a configuration file where I can add desired capabilites and browser configurations . At the moment it's not clear how this is done . Is there an example ?

Integration with Appium

Hi John, this isnt an issue, just wanted to get some help around tweaking this framework to support appium, if you have ever tried launching tests to appium from the world.js or any other way.
Would be great to get few thoughts from you around it.

while installing, show ChromeDriver installation failed Error with http request:

Whole error

Downloading https://chromedriver.storage.googleapis.com/2.28/chromedriver_win32.zip
Saving to C:\GITWOR1\VIMTHI1\AppData\Local\Temp\chromedriver\chromedriver_win32.zip
Receiving...
ChromeDriver installation failed Error with http request: { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-type': 'text/html; charset=utf-8',
'proxy-connection': 'close',
connection: 'close',
'content-length': '756' }
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: node install.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

how to deal with it ?

Reports are not being generated due an error

Hello friends,

I'm experiencing an issue when the tests finished to run successfully or no. When it is trying to generate the HTML report, I get this message:

`/Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/node_modules/cucumber/lib/cucumber/runtime/event_broadcaster.js:30
process.nextTick(function(){ throw error; }); // prevent swallow by unhandled rejection
^

TypeError: node_modules/selenium-cucumber-js/runtime/world.js:191 Cannot read property 'trim' of undefined
at sanitize (/Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/node_modules/cucumber-html-reporter/lib/reporter.js:27:21)
at generateReport (/Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/node_modules/cucumber-html-reporter/lib/reporter.js:52:24)
at Object.generate (/Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/node_modules/cucumber-html-reporter/lib/reporter.js:419:9)
at Object.generateReport [as generate] (/Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/node_modules/cucumber-html-reporter/index.js:30:21)
at /Users/demo/test/Projects/demo/demo.Automated.JS.Tests/node_modules/selenium-cucumber-js/runtime/world.js:207:22
at process._tickCallback (internal/process/next_tick.js:150:11)`

Do you know what library or setup is missing?

Once again, I would like to say THANK YOU for this amazing library.

"--no-colors" OR generic cucumber options

Apologies for being a pest, BUT, for our jenkins test runner, it's very helpful to use the --no-colors option with cucumber otherwise we get a bunch of escape codes like [32m✔ Then the tag "title" should be visible[39m in our output.

So I was wondering if there was a generic mechanism to pass options to cucumber, or do you have to mirror specific options to be passed through?

Thanks once more.

extra failure with new "eyes" integration

I've installed the latest version (1.5.1) with the "eyes" integration -- which i don't actually use.

When i get a failure in my tests, i now also get the following:

Error: Promise factory was not initialized with proper callback
at PromiseFactory.makePromise (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/eyes.utils/src/PromiseFactory.js:49:15)
at EyesBase.abortIfNotClosed (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/eyes.sdk/src/EyesBase.js:968:32)
at /var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-cucumber-js/runtime/world.js:229:33
at ManagedPromise.invokeCallback_ (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-webdriver/lib/promise.js:1341:14)
at TaskQueue.execute_ (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-webdriver/lib/promise.js:2950:14)
at TaskQueue.executeNext_ (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-webdriver/lib/promise.js:2933:27)
at asyncRun (/var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-webdriver/lib/promise.js:2793:27)
at /var/lib/jenkins/workspace/unb-lib-tests/node_modules/selenium-webdriver/lib/promise.js:675:7
at process._tickCallback (internal/process/next_tick.js:109:7)

suggestion: to improve the project

1 - how to use es6.
2 - To cucumber-html-reporter - how to setup metadata
3 - how to customize report

It is really a awesome project
so thank you

chromedriver is out of date

Hi,

The chromedriver you have in your node_modules is .25 which does not support async/await.
The most recent version is .30.

-Lee

Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:61285

I install without errors and run a simple test, I get this error:

1) Scenario: Google search for nothing specific - features/google-search.feature:6
   Step: When I search Google for "nothing specific" - features/google-search.feature:7
   Step Definition: step-definitions/google-search-steps.js:3
   Message:
     Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:61285
         at ClientRequest.<anonymous> (/Users/me/some-project/node_modules/selenium-webdriver/http/index.js:238:15)
         at emitOne (events.js:96:13)
         at ClientRequest.emit (events.js:189:7)
         at Socket.socketErrorListener (_http_client.js:358:9)
         at emitOne (events.js:96:13)
         at Socket.emit (events.js:189:7)
         at emitErrorNT (net.js:1280:8)
         at _combinedTickCallback (internal/process/next_tick.js:74:11)
         at process._tickCallback (internal/process/next_tick.js:98:9)
     From: Task: WebDriver.createSession()
         at Function.createSession (/Users/me/some-project/node_modules/selenium-webdriver/lib/webdriver.js:777:24)
         at Function.createSession (/Users/me/some-project/node_modules/selenium-webdriver/chrome.js:709:29)
         at createDriver (/Users/me/some-project/node_modules/selenium-webdriver/index.js:167:33)
         at Builder.build (/Users/me/some-project/node_modules/selenium-webdriver/index.js:639:16)
         at getDriverInstance (/Users/me/some-project/node_modules/selenium-cucumber-js/runtime/world.js:62:16)
         at /Users/me/some-project/node_modules/selenium-cucumber-js/runtime/world.js:149:29

I am on latest stable macOS and Chrome 57 (also did not work with 56 though).

Any idea where to look at to fix this?

local node packages cause version mis-match errors

Hi,

Thanks again for the shell.
The problem I've run into a couple times is that the two NPM packages you have in a local node_modules are of different (older) versions than what I'm using, which results in mis-matched objects.

Everything works fine if I delete your package-local node_modules.

Any strong reason why page object get created before shared objects?

As in this part of the code world.js:100 the page objects are created before the shared object, therefore if a shared property / method is needed inside of a page object n definition time the system crashes with a not defined error.

Is there is any specific reason why this is done in this way?

I think has more sense to do it in the other way around. Think in the scenario where you would like to create some abstract shared object.

In my case I was trying to augment the object by adding a customised locator, I defined in a utils shared object and when trying to use my customised locator in a page object as defined in the how to, it fails due the page object get created before shared objects.

feature request: command line option to disable report types

We use our test suite as a health-checking framework ("are services a, b, and c online?") which runs every 3 minutes.

While the json report output is useful for us (jenkins integration via the Cucumber Test Result Plugin), neither the junit nor the html reports will ever been looked at.

While this sounds innocuous, the html report generator will write out the screenshots to disk on every failure. These screenshots will never be cleaned up between test suite runs resulting in a bunch of stray files over time.

My work around is to simply delete the screenshots directory as an extra step in our jenkins job, but it would be nice if we could disable the output completely.

Thanks again for this great framework.

Assert and Expect

I want to assert a heading's text on a webpage.
I want to assert "Hi" from the heading.
I tried like this:
this.Then(/^I should see Hi$/m, function(){
driver.wait(until.elementsLocated(by.css('#body-section > div > div.row > div')), 10000);
return driver.findElement(by.css('h3.RTL')).then(function(e){
expect(e.getText()).to.include('Hi');
})
});

Please help...

ExecuteScript result

Hello. I'm having some problem with executing scripts.

Here's a code sample

getDocumentLoadStatus: function () {
let status = driver.executeScript("document.readyState");
console.log(status);
}

I expect "complete" result, but getting such in console:

ManagedPromise {
flow_:
ControlFlow {
propagateUnhandledRejections_: true,
activeQueue_:
TaskQueue {
name_: 'TaskQueue::3',
flow_: [Circular],
tasks_: [Array],
interrupts_: null,
pending_: null,
subQ_: null,
state_: 'new',
unhandledRejections_: Set {} },
taskQueues_: Set { [Object] },
shutdownTask_: null,
hold_:
Timeout {
_called: false,
_idleTimeout: 2147483647,
_idlePrev: [Object],
idleNext: [Object],
idleStart: 437,
onTimeout: [Function],
timerArgs: undefined,
repeat: 2147483647,
destroyed: false,
[Symbol(asyncId)]: 35,
[Symbol(triggerAsyncId)]: 26 } },
stack
: { Task: WebDriver.executeScript()
at thenableWebDriverProxy.schedule (/Users/azadykhin/Code/Wallet/node_modules/selenium-webdriver/lib/webdriver.js:815:17)
at thenableWebDriverProxy.executeScript (/Users/azadykhin/Code/Wallet/node_modules/selenium-webdriver/lib/webdriver.js:886:16)
at Object.waitForDocumentLoad (/Users/azadykhin/Code/Wallet/features/page_objects/dialogue-start-disclaimer.js:17:29)
at createWorld. (/Users/azadykhin/Code/Wallet/features/step_definitions/start.js:53:38)
at combinedTickCallback (internal/process/next_tick.js:131:7) name: 'Task' },
parent
: null,
callbacks
: null,
state
: 'pending',
handled
: false,
value
: undefined,
queue
: null }

Could you please tell me what I'm doing wrong? Thanks

chromdriver version and headless chrome

We're doing some experimenting with headless chrome in place of phantomjs for our testing.

It seems headless chrome needs a pretty recent version of chromedriver. This package currently only gets chromedriver 2.28, and the "getting started with headless chrome" page recommends at least version 2.32 (latest: 2.33)

Any chance for an update?

how to run the repo using just cucumberjs command?

Hi ,

I really like the repo but I want to follow the standard cucumber structure and run from IDE ( from Webstorm).
i followed the steps you mentioned in the intelliJ cucumber plugin section, and I am able to run the repo with command
node ./index.js -s ./features/step_definitions -p ./features/page_objects -o ./features/shared_objects -r ./features/reports

but then when I run the repo using just cucumberjs command, i get various errors. for example it says 'by is not defined'.
can you let me know how to structure the framework so that I can run from command line by just giving cucumberjs or in the intelliJ, right click on the scenario and run the scenario.
I have attached snapshots , how I would like to run. The reason I want to run like this is, its easier to debug and run in one go everything from the editor.. Appreciate your help.
The actual command the editor runs is
./node_modules/.bin/cucumberjs /Users/raja/projects/JavaScript_frameworks/selenium-cucumber-js/features/google-search.feature --format summary --require /Users/raja/projects/JavaScript_frameworks/selenium-cucumber-js/features --require /Applications/WebStorm.app/Contents/plugins/CucumberJavaScript/lib/cucumberjs_formatter_nix.js
(copy pasted from editor)
ideally if i can run with cucumberjs command, then I should be able to figure out how to run in editor.
many thanks.

screen shot 2017-10-20 at 15 12 14 2
screen shot 2017-10-20 at 15 12 27 2
screen shot 2017-10-20 at 15 09 05 2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.