期望数组中的项目 [英] Expect item in array
问题描述
我的一个测试期望错误消息文本是多个值之一.由于 getText()
返回一个 promise 我不能使用 toContain()
茉莉花匹配器.以下将不起作用,因为 protractor
(jasminewd
under-the-hood)不会在匹配器的第二部分 toContain()中解析承诺代码>在这种情况下:
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());
问题:有没有办法用 jasmine+protractor 来检查一个元素是否在一个数组中,其中一个元素是一个承诺?
Question: Is there a way to check if an element is in an array with jasmine+protractor where an element is a promise?
换句话说,我正在寻找 toContain()
的逆,以便 expect()
将隐式解析传入的承诺.
In other words, I'm looking for inverse of toContain()
so that the expect()
would implicitly resolve the promise passed in.
作为一种解决方法,我可以使用 then()
显式解析承诺:
As a workaround, I can explicitly resolve the promise with then()
:
page.errorMessage.getText().then(function (text) {
expect(["Unknown Error", "Connection Error"]).toContain(text);
});
我不确定这是否是最佳选择.我也可以接受基于第三方的解决方案,例如 jasmine-matchers
.
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
.
举个例子,Python中存在这种断言:
As an example, this kind of assertion exists in Python:
self.assertIn(1, [1, 2, 3, 4])
推荐答案
看起来您需要一个自定义匹配器.取决于您使用的 Jasmine 版本:
Looks like you need a custom matcher. Depending on the version of Jasmine you are using:
使用茉莉花 1:
this.addMatchers({
toBeIn: function(expected) {
var possibilities = Array.isArray(expected) ? expected : [expected];
return possibilities.indexOf(this.actual) > -1;
}
});
使用 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
};
}
};
}
});
您必须在将要在其中使用的每个 describe
块的 beforeEach
部分中执行此操作.
You'll have to execute this in the beforeEach
section on each of your describe
blocks it's going to be used in.
您的期望如下:
expect(page.errorMessage.getText()).toBeIn(["Unknown Error", "Connection Error"]);
这篇关于期望数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!