The Problem:
I have an array of promises which is resolved to an array of strings. Now the test should pass if at least one of the strings matches a regular expression.
Currently, I solve it using simple string concatenation:
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(values[0] + values[1] + values[2]).toMatch(/expression/);
});
Obviously, this does not scale well and is not particularly readable.
The Question:
Is is possible to solve it using a custom jasmine matcher, or jasmine.any()
or custom asymmetric equality tester?
If this works,
I think you can write this as follows;
And it's scalable. :)
As said in the comments, although I initially use
map
, reduce would allow you to do what you need, and in this caste at least makes a lot more sense:Or writing the same thing, but using ES6 arrow functions:
Both do the same thing, the reduce callback will default to false, until the
v.match
expression evaluates to true.I'm assuming this is obvious to most people, but I thought I'd provide both syntaxes and some explanation for future reference
Perhaps this solution could be optimized a bit more, to stop matching the pattern once a single match has been found:
All I did was to use the current reduce value as default (once that has been set to true, there's no point in testing any other string value). To ensure
v.match
evaluates to a boolean instead of an array, I just used!!v.match()
. That part is optional though. In ES6, the same thing looks like this:This might perform better with big data sets (considering the
match
calls stop once the first match was found, as opposed tov.match
being called every time).If those [text1, text2, text3] is texts from ElementFinder
.getText()
then you can also to try with Expected Conditions (You know that i am huge fan of EC right? :) ).For simple elements: http://www.protractortest.org/#/api?view=ExpectedConditions.prototype.textToBePresentInElement
For textArea, inputs: http://www.protractortest.org/#/api?view=ExpectedConditions.prototype.textToBePresentInElementValue
Notice, that unfortunatelly .textToBePresentInElement works only with single ElementFinder, ArrayElementFinder is not supported. But in that case you can make something with
.filter()
and assert that returned list is empty.You could simply use
map
to get a list ofboolean
and then assert the result withtoContain(true)
:You could also use a custom matcher:
And the custom matcher declared in
beforeEach
:Array.prototype.some()
looks like what you actually looking for.For more information https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some