The Problem:
我有一个promises数组,它被解析为一个字符串数组。现在,如果至少有一个字符串与正则表达式匹配,则测试应该通过。
目前,我使用简单的字符串连接来解决这个问题:
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(values[0] + values[1] + values[2]).toMatch(/expression/);
});
显然,这不能很好地扩展,而且可读性也不是特别好。
问题:
可以使用自定义的jasmine匹配器或者jasmine.any()
或custom asymmetric equality tester来解决这个问题
发布于 2016-06-29 22:04:37
您可以简单地使用map
来获取boolean
的列表,然后用toContain(true)
断言结果
var all = protractor.promise.all;
var map = protractor.promise.map;
expect(map(all([text1, text2, text3]), RegExp.prototype.test, /expression/)).toContain(true);
您还可以使用自定义匹配器:
expect(all([text1, text2, text3])).toContainPattern(/expression/);
和在beforeEach
中声明的自定义匹配器
beforeEach(function() {
jasmine.addMatchers({
toContainPattern: function() {
return {
compare: function(actual, regex) {
return {
pass: actual.some(RegExp.prototype.test, regex),
message: "Expected [" + actual + "] to have one or more match with " + regex
};
}
};
}
});
});
发布于 2016-06-21 00:00:41
正如评论中所说的,虽然我最初使用的是map
,但reduce会让你做你需要的事情,至少在这个种姓中更有意义:
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(
values.reduce(function(p, v) {
return v.match(/expression/) || p;
}, false)
).toBe(true);
});
或者编写相同的东西,但使用ES6箭头函数:
protractor.promise.all([text1, text2, text3]).then(function(values) {
exptect(
values.reduce( (p, v) => v.match(/expression/) || p, false )
).toBe(true);
});
两者都做同样的事情,reduce回调将缺省为false,直到v.match
表达式计算为true。
我假设这对大多数人来说是显而易见的,但我认为我应该提供语法和一些解释,以供将来参考
也许这个解决方案可以进行更多的优化,一旦找到一个匹配,就停止匹配模式:
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(
values.reduce(function(p, v) {
return p || !!v.match(/expression/);
}, false)
).toBe(true);
});
我所做的就是使用当前的reduce值作为默认值(一旦该值被设置为true,就没有必要测试任何其他的字符串值)。为了确保v.match
的计算结果是布尔值而不是数组,我只使用了!!v.match()
。不过,这部分是可选的。在ES6中,同样的事情看起来是这样的:
protractor.promise.all([text1, text2, text3]).then(function(values) {
exptect(
values.reduce( (p, v) => p || !!v.match(/expression/), false )
).toBe(true);
});
对于大数据集,这可能会执行得更好(考虑到一旦找到第一个匹配,match
调用就会停止,而不是每次都调用v.match
)。
发布于 2016-06-21 02:56:28
如果这行得通
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(values[0] + values[1] + values[2]).toMatch(/expression/);
});
我认为你可以这样写:
protractor.promise.all([text1, text2, text3]).then(function (values) {
expect(values.join('')).toMatch(/expression/);
});
而且它是可扩展的。:)
https://stackoverflow.com/questions/37926523
复制相似问题