Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code in Protractor / AngularJS Testing

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?

like image 478
Jason Avatar asked Jul 16 '14 13:07

Jason


People also ask

Does Protractor Use Jasmine?

By default, Protractor uses the Jasmine test framework for its testing interface. This tutorial assumes some familiarity with Jasmine, and we will use version 2.4. This tutorial will set up a test using a local standalone Selenium Server to control browsers.

What is Node JS in Protractor?

Node. js is package file we are using in protractor automation tool to run the angular. js based application.It contains selenium and other browser drivers to run our applications in different environments.

Does Protractor require Java?

But there is still no way, you can write Protractor tests using Java or Python as Protractor's core is built on Javascript(node. js) and is purely Javascript.


2 Answers

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(...);
});
like image 80
Alexander Puchkov Avatar answered Oct 04 '22 05:10

Alexander Puchkov


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();
        });
    });
}
like image 40
Marshall Bean Avatar answered Oct 04 '22 05:10

Marshall Bean