10

We have several Protractor end to end tests for our AngularJS app in several JS files and they work great. But, there is a lot of duplicated code throughout the tests and we would like to DRY that up.

For instance, every time we log in, we have to click on the text elements, type in the username and password, and then click enter. And right now every single JS file has its own copy of the login function which is called before every test.

It would be nice to refactor those out into modules that we can then import. I have been searching for hours, but not found a good solution.

How should we do this?

2 Answers 2

22

You can create nodejs modules and include them in protractor configuration

login-helpers.js

exports.loginToPage = function () {
    //nodejs code to login
};

protractor.conf.js

exports.config = {
    //...
    onPrepare: function () {
        protractor.loginHelpers = require('./helpers/login-helpers.js');
    }
    //...
};

page.spec.js

it('should do smth', () => {
    protractor.loginHelpers.loginToPage()

    //expect(...).toBe(...);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure login-helpers shouldn't be module.exports.loginToPage = function...
Can you let us know why you bind the loginToPage function onto exports?
1

Our team uses Orchid-js with Jasmine and Protractor, it's designed to do exactly this.

Your test

Describe('Login user',require('../login.js'))("username","password");

login.js

module.exports = function(username,password){ 
    describe('login the user',function(){
        it('should login the user',function(){
            element(by.id('usernameField')).sendKeys(username);
            element(by.id('passwordField')).sendKeys(password);
            element(by.id('loginButton')).click();
        });
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.