Ожидайте состояние внутри - PullRequest
0 голосов
/ 25 апреля 2018

Я использую PageObjects в тестах Protractor. Структура выглядит так,

  • e2e
    • функция
      • base.po.ts // Базовый класс PageObject
      • Войти
        • login.e2e-spec.ts // содержит описание , it блоков и т. Д. И ожидаемые условия.
        • login.po.ts // Взаимодействует с элементами страницы

Я возвращаю Promises из методов внутри PageObject файла. А затем внутри spec файла в it блоков, которые у меня есть Ожидаются условия.

Пример кода похож на

// login.e2e-spec.ts

    it('should logout', () => {
          console.log('---- step 1 ----');
          page.logout().then(function () {
              console.log('---- step 4 ----');
              expect(page.inDom(page.getLoginButton())).toBe(true);
          });
          console.log('---- step 5 ----');
    });



// login.po.ts
public logout() {
        const that = this;
        return new Promise(function (fulfill = null, reject = null) {
            that.clickIfElementIsAvailable(that.welcomeModelCancelButtonElement);
            that.waitForVisibility(that.sideBarOpenerElement).then(function () {
                console.log('---- step 2 ----');
                that.sideBarOpenerElement.click();

                that.waitForVisibility(that.logoutButtonElement).then(function () {
                    console.log('---- step 3 ----');
                    that.logoutButtonElement.click();
                    fulfill();

                }, reject);

            }, reject);
        });
    }

После выполнения все тесты проходят, и я получаю следующий вывод в журнале.

---- step 1 ----
---- step 5 ----
(node:2639) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'waitForElement' of undefined
(node:2639) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.


3 specs, 0 failures

На практике у меня есть несколько тестов, поэтому управление просто переходит к следующим тестам и в конце говорит, что все тесты пройдены успешно.

Теперь я понимаю, что управление помещает команды в очередь и продвигается вперед. Как я могу справиться с этой ситуацией? Что я делаю не так? Спасибо.

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Вам нужно разрешить обещание, прежде чем проверять ожидаемое значение некоторые

page.getLoginButton (). Затем (функция (статус) {

* * 1004 ожидают (состояние) .toBe (истина); })
0 голосов
/ 02 мая 2018

Я также опубликовал проблему в репозитории Protractor github и получил это решение от IgorSasovets

Используйте инструкцию Return на каждом обещании. Текущий код выглядит так,

public logout() {
    const that = this;
    return that.clickIfElementIsAvailable(that.welcomeModelCancelButtonElement)
        .then(() => that.waitForVisibility(that.sideBarOpenerElement))
        .then(() => {
            console.log('---- step 2 ----');
            return that.sideBarOpenerElement.click();
        })
        .then(() => that.waitForVisibility(that.logoutButtonElement))
        .then(() => {
            console.log('---- step 3 ----');
            return that.logoutButtonElement.click();
        });
}



it('should logout', () => {
      console.log('---- step 1 ----');
      return page.logout().then(() => {
          console.log('---- step 4 ----');
          expect(page.inDom(page.getLoginButton())).toBe(true);
          console.log('---- step 5 ----');
      });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...