programing

트랙터에서 약속 만들기 및 해결하기

css3 2023. 10. 12. 23:26

트랙터에서 약속 만들기 및 해결하기

Protractor를 이용하여 Angular app의 페이지에 스토어 정보를 추가하는 테스트 케이스를 작성합니다.처음에는 이미 보유하고 있는 스토어의 수를 세고 테스트 블록이 완료된 후에는 카운트가 1개 증가할 것으로 예상하므로 Protractor에서 약속을 만들고 조작하는 링크를 따라 이 작업을 수행하고 있습니다.

describe('myApp', function() {
  var items,startCount;

  var testPromise = function(){
    items = element.all(by.repeater('store in storelist'));
    var deferred = protractor.promise.defer();
    items.count().then(function(orgCount){
       startCount = orgCount;
       console.log('Start Count: '+ startCount); //prints correct value e.g, 6
    }, function(error){
       console.log(error);
    });
    return deferred.promise;
  };

it('should accept valid data for adding new store', function() {
   var cNum = null;
   testPromise().then(function(result){
      cNum = result;
      console.log('cNUm value: '+ cNum); //this value doesn't get printed in console
   });
   /* Code for adding test fields in store page */

   expect(items.count()).toBe(cNum+1);
 });
});

테스트가 끝날 때 스토어 카운트가 동일할 것으로 예상합니다. count()는 약속을 해결하는 것이며 올바른 스토어 카운트 값이 testPromise()에 인쇄되지만 testPromise()를 호출하면 해당 블록에 인쇄됩니다. 그 다음 메서드는 해당 '그때' 블록에 들어가지 않습니다.

그리고 최종 결과는 다음과 같이 말합니다.

Message:
 Expected 6 to be 1.
 Stacktrace:
  Error: Failed expectation

저는 웹드라이버 약속에 대해서도 조금 더 알아봤습니다.이 링크 http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_promise_Promise.html 의 Promise()를 사용하여 약속을 만들고 가치를 해결하려고 했지만 문제가 무엇인지 확실하지 않습니다.'6은 NaN으로 예상됨' 또는 '6은 1로 예상됨'이라는 오류 메시지가 표시됩니다. 약속을 해결하지 않거나 '그때' 블록을 올바르게 쓰는 것입니까?이 문제에 대한 통찰력/도움을 주시면 감사하겠습니다.

창조.

트랙터에서 약속을 만들려면 다음과 같이 적어야 합니다.

var deferred = protractor.promise.defer();
var promise = deferred.promise;

콜백

콜백은 비동기적으로 호출됩니다."성공 시" 콜백을 하나 이상 등록할 수 있습니다.

promise.then(function() {
   ...
});

오류 시 콜백을 하나(또는 그 이상) 등록할 수도 있습니다.

promise.then(null, function() {
   ...
});

다음 등록은 체인으로 연결될 수 있습니다.

promise.then(function() {
   ...
}).then(function() {
   ...
}).then(null, function() {
   ...
}).then(function() {

}, function() {
   ...
}).then(onSuccess, onFailure);

결의안

성공.

"성공 시" 콜백은 약속이 성공적으로 해결될 때 호출됩니다.

deferred.fulfill(value);

실패.

"실패 시" 콜백은 약속이 성공적으로 해결될 때 호출됩니다.

deferred.reject(new Error('a problem occurs'));

당신의 코드에

해결 단계를 놓쳤군요당신은 약속을 이행해야 합니다.

Webdriver.js 설명서에서 더 완벽한 참조가 가능합니다.

약속을 만들고 이행(또는 거부)하는 Protractor에서 사용하기 위한 사용자 정의 함수의 작동 예는 다음과 같습니다.

// 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()메소드 자체가 약속을 반환합니다.에 성공적으로 전화를 걸었을 때getText(), 텍스트를 정수로 파싱하고 약속을 이행합니다. 만약에getText()거부, 우리는 이유를 우리 자신의 거부 요청에 전달합니다.

이 함수를 사용하려면 요소 약속을 전달합니다.

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);

동일한 이슈를 받고 예상 아이템 개수에 대한 약속을 만들어 해결했습니다.

it('should accept valid data for adding new store', function() {
    // Given
    let expectedCountAfterNewRow = items.count().then((cnt)=>{return cnt+1}); 
    // Note: items.count() is a promise so the expected count should a promise too

    // When
    /* Code for adding test fields in store page */

    // Then
   expect(items.count()).toEqual(expectedCountAfterNewRow);
});

언급URL : https://stackoverflow.com/questions/24289431/creating-and-resolving-promises-in-protractor