量角器比较字符串数字

Protractor compare string numbers

今天我遇到了为非常简单的行为创建测试的有趣问题:'Most recent' 排序。测试需要知道的所有内容:

  1. 每个项目都有 ID
  2. 在这种排序情况下,上一个 ID 小于下一个 ID

方法:将 ID 写入项目的属性,使用 getAttribute() 从第一个项目获取该 ID,第二个采用任何一种方式。

问题getAttribute() promise 产生的字符串值和 Jasmine 无法比较(从框中)字符串数字。

我想找到一种优雅的方式来将它们与 toBeLessThan() 进行比较,而不是使用少数 .then() 链来比较这些东西。

Root of no-type-definition evil

谢谢大家 <3

一种方法是使用 自定义 jasmine 匹配器:

toBeSorted: function() {
    return {
        compare: function(actual) {
            var expected = actual.slice().sort(function (a, b) {
                return +a.localeCompare(+b);
            });

            return {
                pass: jasmine.matchersUtil.equals(actual, expected)
            };
        }
    };
},

此处匹配器采用实际输入数组,对其进行整数排序并与输入数组进行比较。

用法:

expect(element.all(by.css(".myclass")).getAttribute("id")).toBeSorted();

请注意,这里我们在 ElementArrayFinder 上调用 getAttribute("id"),它将解析为 id 属性值的数组。 expect() 本身已修补以隐式解析承诺。

您可以创建一个辅助函数将字符串数字转换为实际数字,这将使用 Promises:

function toNumber(promiseOrValue) {

    // if it is not a promise, then convert a value
    if (!protractor.promise.isPromise(promiseOrValue)) {
        return parseInt(promiseOrValue, 10);
    }

    // if promise - convert result to number
    return promiseOrValue.then(function (stringNumber) {
        return parseInt(stringNumber, 10);
    });
}

然后将结果与 .toBeLessThan 等一起使用:

expect(toNumber(itemId)).toBeLessThan(toNumber(anotherItemId));

我忘记了 promises 的固有性质,但感谢 Michael Radionov 我记得我想做什么。

expect(first.then( r => Number(r) )).toBe(next.then( r => Number(r) ));

我猜这笔画看起来很简单。

更新

ES6:

it('should test numbers', async function () {
    let first = Number(await $('#first').getText());
    let second = Number(await $('#second').getText());
    expect(first).toBeGreaterThan(second);
})