在执行测试之前,等待自己的函数(返回承诺) [英] Wait for an own function (which returns a promise) before tests are executed

查看:68
本文介绍了在执行测试之前,等待自己的函数(返回承诺)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是赛普拉斯的新手,正在尝试弄清事物的工作原理.

I'm new to cypress and am trying to figure out how things work.

我有自己的功能(该功能调用测试控制器服务器来重置数据库).它会返回一个诺言,该诺言将在成功重置数据库后完成.

I have my own function (which calls a test controller server to reset the database). It returns a promise which completes when the DB have been successfully resetted.

function resetDatabase(){
  // returns a promise for my REST api call.
}

我的目标是能够在所有测试之前执行它.

My goal is to be able to execute it before all tests.

describe('Account test suite', function () {

  // how can I call resetDb here and wait for the result
  // before the tests below are invoked?

  it('can log in', function () {
        cy.visit(Cypress.config().testServerUrl + '/Account/Login/')

        cy.get('[name="UserName"]').type("admin");
        cy.get('[name="Password"]').type("123456");
        cy.get('#login-button').click();
  });

  // .. and more test

})

我如何在柏树中做到这一点?

How can I do that in cypress?

更新

我尝试过

  before(() => {
    return resetDb(Cypress.config().apiServerUrl);
  });

但随后我得到警告:

Cypress检测到您在测试中返回了一个Promise,但还调用了该Promise中的一个或多个cy命令

Cypress detected that you returned a promise in a test, but also invoked one or more cy commands inside of that promise

我没有在 resetDb()中调用 cy .

推荐答案

赛普拉斯有承诺(鸭子打字.实际上,赛普拉斯并不完全符合真实的承诺,它们可能会或可能不会起作用.

Cypress have promises (Cypress.Promise), but they are not real promises, more like duck typing. In fact, Cypress isn't 100% compatible with real promises, they might, or might not, work.

Cypress.Promise 视为任务或动作.它们与所有其他cypress命令顺序执行.

Think of Cypress.Promise as a Task or an Action. They are executed sequentially with all other cypress commands.

要使功能进入赛普拉斯管道,可以使用自定义命令.该文档没有说明,但是您可以从中返回 Cypress.Promise .

To get your function into the Cypress pipeline you can use custom commands. The documentation doesn't state it, but you can return a Cypress.Promise from them.

Cypress.Commands.add('resetDb', function () {
  var apiServerUrl = Cypress.config().apiServerUrl;
  return new Cypress.Promise((resolve, reject) => {
    httpRequest('PUT', apiServerUrl + "/api/test/reset/")
      .then(function (data) {
        resolve();
      })
      .catch(function (err) {
        reject(err);
      });
  });
});

然后可以从测试本身执行该命令,或者像我在 before()中那样执行该命令.

That command can then be executed from the test itself, or as in my case from before().

describe('Account', function () {
  before(() => {
    cy.resetDb();
  });

  it('can login', function () {
    // test code
  });

})

这篇关于在执行测试之前,等待自己的函数(返回承诺)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆