Подождать при двух условиях, пока одно не удастся - PullRequest
0 голосов
/ 14 сентября 2018

Я использую TestCafe и не могу реализовать это поведение:

  1. Войдите на мой сайт, используя механизм Role
  2. Проверьте условия:
    • изменение URL ИЛИ
    • Появляется сообщение об ошибке

Я знаю, как получить текущий URL с помощью ClientFunction и проверить видимость элемента с помощью Selector, но я не могу понять, как их смешать.

Возможно ли это?


Основываясь на ответе NoriSte (спасибо!), Рабочий образец адаптирован из моего варианта использования. Я не нашел его ни элегантным, ни расширяемым (что делать, если вы хотите ИЛИ больше условий).

AuthPage.js

import { Selector, t, Role, ClientFunction } from "testcafe"

const url = 'http://localhost:8081'
const loginUrl = `${url}/login`;
const logoutUrl = `${url}/logout`;

const loginInput = Selector('[data-qa="login input"]');
const passwordInput = Selector('[data-qa="password input"]');
const submitButton = Selector('[data-qa="submit button"]')
const loginError = Selector('[data-qa="login error"]');

const getLocation = ClientFunction(() => document.location.href.toString());

const login = (username, password) => async tt =>
  await tt
    .typeText(loginInput, username)
    .pressKey('tab')
    .typeText(passwordInput, password)
    .click(submitButton);

export default class AuthPage {
  constructor () {
    this.roles = {
      // 'almighty god': Role(loginUrl, login('filou', 'filoucfou')),
      // 'bad mutafuka': Role(loginUrl, login('badbadbad', 'password'))
      // Can't use Role, don't know why ?!
      'almighty god': login('gooood', 'password'),
      'bad mutafuka': login('badbadbad', 'password')
    }
  }

  async loginWith (roleName) {
    const oldUrl = await getLocation();

    // await t
    //   .useRole(this.roles[roleName]);
    // Does weird thing, not what i would expect
    await this.roles[roleName](t)
    if (await loginError.with({ timeout: 5000, visibilityCheck: true }).exists) {
      console.log('login error:', oldUrl)
      return {url: oldUrl, login: false};
    }

    await t
      .wait(10000);

    const newUrl = await getLocation()
    return {url: newUrl, login: oldUrl !== newUrl};
  }
}

test.js

import LoginPage from 'AuthPage'

fixture `sinoc-fixture`
  .page `http://localhost:8081`;

const loginPage = new LoginPage()

test('Login with wrong credentials should fail', async (t) => {
  const result = await loginPage.loginWith('bad mutafuka')
  await t
    .expect(result.login === false).ok()
});

test('Login with good credentials should succeed', async (t) => {
  const result = await loginPage.loginWith('almighty god')
  await t
    .expect(result.login === true)
    .ok()
    .expect(result.url)
    .contains('/dashboard');
});

Ответы [ 2 ]

0 голосов
/ 18 сентября 2018

Я получил ClientFunction, опросив 2 условия:

const getLocationAndError = ClientFunction(({url}) => {
  return new Promise(resolve => {
    (function polling() {
      const errorModal = document.querySelector('[data-qa="login error"]');
      const newUrl = document.location.href.toString();
      const navigated = newUrl !== url;
      if (errorModal || navigated) {
        resolve({navigated, loginError: !!errorModal, url: newUrl});
      } else {
        setTimeout(polling, 200);
      }
    })();
  });
});
0 голосов
/ 14 сентября 2018

У вас есть общедоступная страница, где я могу ее протестировать?В любом случае, я разработал этот код, но я не уверен, что он соответствует вашим потребностям, и он не работает ...

import { ClientFunction } from 'testcafe';
const getLocation = ClientFunction(() => document.location.href);

test('redirect OR error', async t => {
    let errorMesageDidAppear = false;
    let didRedirect = false;

    const oldUrl = getLocation();

    await t.useRole(yourUser)

    // If a redirect happens TestCafe automatically waits for it
    // @see http://devexpress.github.io/testcafe/documentation/test-api/built-in-waiting-mechanisms.html#waiting-for-redirects
    // if it doesn't happen TestCafe goes ahead with the test

    const newUrl = getLocation();

    didRedirect = newUrl !== oldUrl;
    if(!didRedirect) {
        await Selector('#ERROR_BOX_ID').with({ visibilityCheck: true })();
        errorMesageDidAppear = true;
        // if it doesn't appear the test will fail due to the timeout limit
    }

    // now you have two flags: didRedirect and errorMesageDidAppear
});

Я напоминал код, показанный здесь Ожидание элементов при оценке селекторов и эти инструкции

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...