18

I am looking to create reusable components within my nightwatch.js tests.

ie. login to the web app, logout of the web app

What is the best method / pattern for creating these steps in a reusable way?

chrisphilton
  • 459
  • 3
  • 7
  • 1
    I believe page objects and custom commands both provide reusability. For reusable components such as login, logout, custom commands can be used. But for creating truly elaborate end to end test scenarios page objects would be the way to go, becuase it's likely that there are repeated test steps as you move through the application. – daredadevil Apr 06 '17 at 00:30
  • 1
    In case you don't have to use the hopeless Nightwatch, Python/behave has what you need - "execute_steps" command. – Alichino Sep 24 '19 at 09:37

3 Answers3

30

You can create custom commands for that: http://nightwatchjs.org/guide#writing-custom-commands

  1. in nightwatch.json specify the path to the folder that will contain your custom command file
  2. create a js file and name it how your custom command should be names (ie login.js)
  3. write the code you need:

exports.command = function(username, password) {
    
    this
        .waitForElementVisible('#password', 4000)
        .setValue('#password', password)
        .waitForElementVisible('#username', 1000)
        .setValue('#username', username)
        .waitForElementVisible('#sign_in', 1000)
        .click('#sign_in')
        .waitForElementVisible('h1.folder-title', 10000)
        
        return this;
};
  1. use the custom command in your test:

.login("your_username", "your_password")
4

This is typically done with page objects. http://nightwatchjs.org/guide#page-objects

Then you can just

var myPage = client.page.myPage();

myPage.navigate()
  .assert.title('MyPage')
  .login('foo', 'bar)
  .assert.displayName('foo');
Jkarttunen
  • 2,613
  • 1
  • 17
  • 21
-1

To add to the previous answer, you can also create custom assertions and reporters in addition to commands.

The Nightwatch Guide has more information on customization and extending Nightwatch.