Ravi
Ravi

Reputation: 101

How to combine multiple expect conditions in protractor?

I have a protractor-jasmine test where I am trying to check that all the fields on the page are blank. I wrote a simple test using for loop that works. Now, my problem is that I am trying to adhere to protractor/jasmine best practices which say to have only one test per expect conditions. How do I change this code to only one expect conditions?

Here is the test I wrote:

it("should check that all input fields are blank", function() {
    allInputs.then(function(elements) {
        elements.forEach(function(element){
            expect(element.getText()).toEqual("");
        });
    });
});

Upvotes: 3

Views: 9623

Answers (1)

AdityaReddy
AdityaReddy

Reputation: 3645

In Short: You can just do this - expect(allInputs.getText()).toEqual("").

More Details: element.all().getText() returns an array containing the text values of all the child elements and since you are expecting the values to be blank, Just check if the total string is blank.

To answer you generic question of

"How do we handle a scenario when we have need multiple validations to be performed"

Expected Conditions provide conditional options - like OR, AND etc. Refer the official documentation here

var EC = protractor.ExpectedConditions;
var titleContainsFoo = EC.titleContains('Foo');
var titleIsNotFooBar = EC.not(EC.titleIs('FooBar'));
// Waits for title to contain 'Foo', but is not 'FooBar'
browser.wait(EC.and(titleContainsFoo, titleIsNotFooBar), 5000);

In case you would like to group multiple expects

Promise.all[
expect(allInputs.getText()).toEqual(""),
expect(allOutputs.getText()).toEqual("")
].then(function(){
   done();
  })

UPDATE 1: Promise.all syntax above was incorrect. It should be Promise.all([Array of Promises]) where I had the curled braces missing.

This is the correct way of doing it

describe('Describe something', function() {
    it('check check', function(done) {
        browser.get('http://www.protractortest.org/#/')
        Promise.all([
            expect(browser.getCurrentUrl()).toContain('protractortest'),
            expect(browser.getCurrentUrl()).toContain('org')]).then(function() {
            done();
        }).catch(function() {
            done.fail('somehow the Url is incorrect');
        })
        browser.sleep(10000)
    });
});

This gives us the flexibility to group all the validations in a test case into a single Promise(provide all promises returned by expects in an Array). This will help us group all the assertions and Pass/Fail the test case and throw a custom error message for all the set of Validations

UPDATE 2: As I mentioned above. element.all().getText() returns an array and to compare, I incorrectly compared an Array object to String object.We need to do a array.join() and compare

 allInputs.getText().then(function(values){
    expect(values.join('')).toEqual('')
})

Upvotes: 3

Related Questions