Dennis Ferguson Dennis Ferguson - 2 months ago 6
AngularJS Question

How to pass a variable to javascript in nested function

I have several protractor / angularjs it blocks that repeat the same bit of code that I would like to put inside a function. I want to just call the function instead of repeating this over and over.

it('should move directly to Draft', function() {
posting_sum_page.locate_action_button.click();
posting_action_page.move_action.filter(function(elem) {
return elem.getText().then(function(text) {
return text === 'Draft';
});
}).click();
});


This part of the block is the repeated part I want to create a function for. I am new to javascript so this is eluding me on how to do this.

return elem.getText().then(function(text) {
return text === 'Draft';
});
}).click();


I need to be able to substitute 'Draft' with different variables. I am using page objects for part of this and I am not sure A) how to create a function like this and pass in my text & B) if it should go on the spec side or the page side? This is probably pretty basic for most folks. But since I am new to javascript I am having trouble wrapping my head around this.

Answer

I would extract the whole filter function into a "helpers" module.

helpers.js:

var Helpers = function () {
    this.filterByText = function (text) {
        return function (elem) {
            return elem.getText().then(function(actualText) {
                return actualText === text;
            });
        };
    }
}

module.exports = new Helpers();

Usage in the test:

var helpers = require("helpers");

describe("My Test", function () {
    it('should move directly to Draft', function() {
        posting_sum_page.locate_action_button.click();
        posting_action_page.move_action.filter(helpers.filterByText('Draft')).click();
    });
});