Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Expect item in array

One of my test expects an error message text to be one of multiple values. Since getText() returns a promise I cannot use toContain() jasmine matcher. The following would not work since protractor (jasminewd under-the-hood) would not resolve a promise in the second part of the matcher, toContain() in this case:

expect(["Unknown Error", "Connection Error"]).toContain(page.errorMessage.getText());

Question: Is there a way to check if an element is in an array with jasmine+protractor where an element is a promise?

In other words, I'm looking for inverse of toContain() so that the expect() would implicitly resolve the promise passed in.


As a workaround, I can explicitly resolve the promise with then():

page.errorMessage.getText().then(function (text) {
    expect(["Unknown Error", "Connection Error"]).toContain(text);
});

I'm not sure if this is the best option. I would also be okay with a solution based on third-parties like jasmine-matchers.


As an example, this kind of assertion exists in Python:

self.assertIn(1, [1, 2, 3, 4]) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like you need a custom matcher. Depending on the version of Jasmine you are using:

With Jasmine 1:

this.addMatchers({
    toBeIn: function(expected) {
        var possibilities = Array.isArray(expected) ? expected : [expected];
        return possibilities.indexOf(this.actual) > -1;
    }
});


With Jasmine 2:

this.addMatchers({
    toBeIn: function(util, customEqualityTesters) {
        return {
            compare: function(actual, expected) {
                var possibilities = Array.isArray(expected) ? expected : [expected];
                var passed = possibilities.indexOf(actual) > -1;

                return {
                    pass: passed,
                    message: 'Expected [' + possibilities.join(', ') + ']' + (passed ? ' not' : '') + ' to contain ' + actual
                };
            }
        };
    }
});


You'll have to execute this in the beforeEach section on each of your describe blocks it's going to be used in.

Your expect would look like:

expect(page.errorMessage.getText()).toBeIn(["Unknown Error", "Connection Error"]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...