这是一个用于Protractor中的用户定义函数的工作示例,该函数创建并实现(或拒绝)promise:
// Get the text of an element and convert to an integer.// Returns a promise.function getTextAsInteger(element, radix) { // Specify a default radix for the call to parseInt. radix = radix || 10; // Create a promise to be fulfilled or rejected later. var deferred = protractor.promise.defer(); // Get the text from the element. The call to getText // returns a promise. element.getText().then( function success(text) { var num = parseInt(text, radix); if (!isNaN(num)) { // Successfully converted text to integer. deferred.fulfill(num); } else { // Error converting text to integer. deferred.reject('could not parse "$1" into an integer' .replace('$1', text)); } }, function error(reason) { // Reject our promise and pass the reason from the getText rejection. deferred.reject(reason); }); // Return the promise. This will be resolved or rejected // when the above call to getText is resolved. return deferred.promise;}该函数以
element参数为参数,并调用其
getText()方法,该方法本身返回一个Promise。成功调用时
getText(),将文本解析为整数并兑现承诺。如果
getText()拒绝,我们会将原因传递给我们自己的拒绝电话。
要使用此功能,请传递一个元素promise:
var numField = element(by.id('num-field'));getTextAsInteger(numField).then( function success(num) { console.log(num); }, function error(reason) { console.error(reason); });要么:
var numField = element(by.id('num-field'));expect(getTextAsInteger(numField)).toEqual(jasmine.any(Number));expect(getTextAsInteger(numField)).toBeGreaterThan(0);


