programing

상태를 어떻게 기다리죠?

javamemo 2023. 3. 1. 08:48
반응형

상태를 어떻게 기다리죠?

저는 처음 접하는 사람이고, e2e 테스트를 시행하려고 합니다.이게 옳은 방법인지는 모르겠지만...테스트하고 싶은 페이지는 전체 각 페이지 베이스가 아니기 때문에...문제가 좀 있어요.

첫 번째 사양은 다음과 같습니다.

describe('should open contact page', function() {
var ptor = protractor.getInstance();

beforeEach(function(){

   var Login = require('./util/Login');
   new Login(ptor);
});

이 로그인 클래스를 만들었습니다만, 로그인 후에 연락처 페이지를 열고 싶은데, 페이지가 완전히 로드되기 전에 바로 요소를 찾으려고 합니다.

사용하려고 했습니다.

browser.driver.wait(function() {

    expect(browser.findElement(by.xpath("//a[@href='#/contacts']")).isDisplayed());
    ptor.findElement(by.xpath("//a[@href='#/contacts']")).click();

});

근데 안 먹히는데...항상 페이지가 로드되기 전에 요소를 찾으려고 합니다.이것도 해봤어요.

browser.driver.wait(function() {
    expect(ptor.isElementPresent(by.xpath("//a[@href='#/contacts']")));          
    ptor.findElement(by.xpath("//a[@href='#/contacts']")).click();
});

할 수 browser.sleep();★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★감히 히는 ???로그인 클래스에는 다음이 있습니다.

ptor.ignoreSynchronization = true;

수 ?@href='#/contacts릭하 기에 에떻 떻떻? ???

【젝젝】1.7.0에는 다음과 같은 신기능도 도입되었습니다.예상되는 조건

명시적으로 대기해야 할 몇 가지 사전 정의된 조건이 있습니다.요소가 나타날 때까지 기다리는 경우:

var EC = protractor.ExpectedConditions;

var e = element(by.id('xyz'));
browser.wait(EC.presenceOf(e), 10000);

expect(e.isPresent()).toBeTruthy();

다음 항목도 참조하십시오.

드디어 알게 됐어...

   var waitLoading = by.css('#loading.loader-state-hidden');

   browser.wait(function() {
       return ptor.isElementPresent(waitLoading);
   }, 8000);

   expect(ptor.isElementPresent(waitLoading)).toBeTruthy();

   var openContact = by.xpath("//a[@href='#/contacts']");
   element(openContact).click();

이 절단기를 사용하면 로드 페이지가 사라질 때까지 요소를 기다릴 수 있습니다.XD를 도와주신 분들께 감사드립니다.

저는 당신이 가장 오래 전부터 굴절기를 사용하면서 같은 문제를 겪었습니다.e2e 테스트에서는 각이 없는 어플리케이션에서 시작하여 각진 부분으로 들어갔다가 다시 각이 없는 부분으로 돌아갑니다.일을 까다롭게 만들었지핵심은 약속과 약속의 작동 방식을 이해하는 것입니다.다음은 기능하는 e2e 테스트의 실제 코드 예입니다.이것으로 테스트를 어떻게 구성할지 알 수 있기를 바랍니다.아마 이 코드의 나쁜 관행일 것입니다만, 부디 이것을 개선해 주세요.하지만 그것이 효과가 있는 것은 알고 있습니다.최선의 방법은 아닐지도 모릅니다.

각도에 도달하려면

var ptor;
var events = require('events');
var eventEmitter = new events.EventEmitter();
var secondClick = require('./second-click');

beforeEach(function () {
    browser.driver.get('http://localhost:8080/');
},10000);

it("should start the test", function () {
    describe("starting", function () {
        it("should find the  link and start the test", function(){
            var elementToFind = by.linkText('Start'); //what element we are looking for
            browser.driver.isElementPresent(elementToFind).then(function(isPresent){
                expect(isPresent).toBe(true); //the test, kind of redundant but it helps pass or fail
                browser.driver.findElement(elementToFind).then(function(start){
                    start.click().then(function(){ //once we've found the element and its on the page click it!! :) 
                        ptor = protractor.getInstance(); //pass down protractor and the events to other files so we can emit events
                        secondClick(eventEmitter, ptor); //this is your callback to keep going on to other actions or test in another file
                    });
                });
            });
        });
    });
},60000);

각도에서는 이 코드가 동작합니다.

 describe("type in a message ", function(){
        it("should find and type in a random message", function(){
            var elementToFind = by.css('form textarea.limited');
            browser.driver.isElementPresent(elementToFind).then(function(isPresent){
                element(elementToFind).sendKeys(randomSentence).then(function(){
                    console.log("typed in random message");
                    continueOn();
                });
            });
        });
    },15000);

각도 종료 후

browser.driver.wait(function(){
   console.log("polling for a firstName to appear");
   return    browser.driver.isElementPresent(by.name('firstName')).then(function(el){
         return el === true;
       });
     }).
   then(function(){
       somefunctionToExecute()
    });

그것이 당신에게 도움이 되고 도움이 되기를 바랍니다!

browser.driver.wait(function() {
    return browser.driver.isElementPresent(by.xpath("//a[@href='#/contacts']"));
});

이 방법은 (타임아웃 파라미터가 없는 경우) 나에게도 유효합니다.

자세한 내용은 http://angular.github.io/protractor/#/api?view=webdriver.WebDriver.protype.wait를 참조하십시오.

위의 답변 덕분에 사용법을 간소화하고 갱신할 수 있었습니다.

function waitFor (selector) {
  return browser.wait(function () {
    return browser.isElementPresent(by.css(selector));
  }, 50000);
}

ng-app에서<html>tag (코드의 이 부분이 당신의 관리 하에 있는 것을 확인)이것에 의해, 많은 초기화 타이밍의 문제가 해결되었습니다.

테스트 케이스가 실패했을 경우 특정 요소에 적절한 오류 메시지를 표시하는 데 도움이 되는 프로젝터에서 대기 조건을 사용하는 가장 좋은 방법

const EC = ExpectedConditions;
const ele = element(by.xpath(your xpath));

return browser.wait(EC.visibilityOf(ele),9000,'element not found').then(() => {
            ele.click();
         });

아무도 이 솔루션을 추가하지 않은 것이 놀랍습니다.기본적으로 모달 다이얼로그를 사용하고 있는 경우는, 요소가 표시되고 클릭할 수 있지만, 그 앞에 모달 다이얼로그가 있기 때문에 클릭할 수 없는 경우가 많습니다.이는 각도기가 각도보다 빠르게 이동하며 각도가 모달(modal)을 닫는 동안 다음 요소를 클릭할 준비가 되었기 때문입니다.

사용하는 것을 추천합니다.

public async clickElementBug(elementLocator: Locator) {
const elem = await element(elementLocator);
await browser.wait(
  async function() {
    try {
      await elem.click();
      return true;
    } catch (error) {
      return false;
    }
  },
  this.TIMEOUT_MILLIS,
  'Clicking of element failed: ' + elem
);

}

브라우저로 이동합니다.기다림은 너무 평범하게 들릴지 모르지만, 그렇지 않아요!

browser.wait가는 길이에요.대기 조건이 있는 함수를 전달하기만 하면 됩니다.예를 들어 페이지에 애니메이션이 로드되지 않을 때까지 기다립니다.

let $animation = $$('.loading');

await browser.wait(
  async () => (await animation.count()) === 0, // function; if returns true it stops waiting; can wait for anything in the world if you get creative with it
  5000, // timeout
  `message on timeout` // comment on error
);

꼭 사용하세요await

또한 기존 라이브러리를 사용할 수도 있습니다.ExpectedConditions미리 정의된 조건들이 많이 있습니다.

그걸로 뭘 할 수 있을지 상상도 못 할 거야

제가 좋아하는 몇 가지입니다.

브라우저 탭 수가 2가 될 때까지 기다리다

// wait until the number of browser's tab's is 2
await browser.wait(
  async () => {
    let tabCount = await browser.getAllWindowHandles();
    return tabCount.length === 2;
  },
  5000,
  'the url didnt open in a new window'
);

750ms까지 애니메이션 로딩이 종료될 때까지 기다리다

// wait until the loading animation is gone for at last 750ms
await browser.wait(
  async () => (await this.$$loadAnimations.count()) === 0 && !(await browser.sleep(750)) && (await this.$$loadAnimations.count()) === 0,
  5000,
  `waiting timeout`
);

임의의 수의 요소가 존재하기를 기다리다

// wait for any number of elements to be present
async waitForElements($elem, timeout = 120000, start = +new Date()) {
    let conditions = [];

    for (let i = 0; i < $elem.length; i++) {
        conditions.push(ExpectedConditions.presenceOf($elem[i]));
    }

    await browser.wait(
        ExpectedConditions.and(...conditions), 
        remainingTimeout(timeout, start), 
        `wait for all elements`
    );
}

// and use

await waitForElements([
  $usernameField, 
  $passwordFiend, 
  $submitButton
])

언급URL : https://stackoverflow.com/questions/22072327/how-can-i-wait-for-a-condition

반응형