TAGS :Viewed: 6 - Published at: a few seconds ago

[ Webdriver.io - how to use beforeEach hooks in the config ]

I am building an app using the MEAN stack and Webdriver for testing.

At the moment I am cleaning the database between tests by using Mocha's beforeEach and afterEach hooks, e.g.:

describe('Links', function() {
  // drop DB collections

  beforeEach(function(done){
    //create database objects
  });

  afterEach(function(done){
    // drop DB collections
  });
});

Is there a way of setting up wdio.conf.js for this to happen before and after each of my tests automatically? The config's before: and after: function() {} run as a beforeAll / afterAll rather than for each test.

Answer 1


Yes, see this url: http://webdriver.io/guide/testrunner/gettingstarted.html

if you launch the wdio config, will generate a file named wdio.conf.js, on this file exists functions to launch scripts after or before the tests, i show the example of the functions contains this file:

// =====
// Hooks
// =====
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO
// will wait until that promise got resolved to continue.
//
// Gets executed before all workers get launched.
onPrepare: function() {
    // do something
},
//
// Gets executed before test execution begins. At this point you will have access to all global
// variables like `browser`. It is the perfect place to define custom commands.
before: function() {
    // do something
},
//
// Gets executed after all tests are done. You still have access to all global variables from
// the test.
after: function(failures, pid) {
    // do something
},
//
// Gets executed after all workers got shut down and the process is about to exit. It is not
// possible to defer the end of the process using a promise.
onComplete: function() {

    // do something
}

Is important, if you launch a script asynchronous, and you wait the callback in the moment of clean the database so you need a promise, else the next step hook will launch not waiting the previous function hook, example:

    onPrepare: function() {
    return new Promise(function(resolve, reject) {
        sauceConnectLauncher({
          username: 'the_pianist2',
          accessKey: '67224e83a-1cf7440d-8c88-857c4d3cde49',
        }, function (err, sauceConnectProcess) {
            if (err) {
                return reject(err);
            }
            console.log('success');
            resolve();
        });
    });


},