使用 Cypress 测试依赖 OAuth 的应用程序

use*_*554 5 testing oauth-2.0 cypress

我继承了一个使用 OAuth 的 Node.js Web 应用程序。每当您访问页面时,应用程序都会确保您已通过身份验证。请注意,这里没有 Angular、React、Vue 等。每个页面都是直接的 HTML。

我想使用Cypress测试这个网站。我的问题是,我陷入了来自身份验证提供商的初始重定向。Cypress 承认OAuth 是一个挑战

命令.js

Cypress.Commands.add('login', (credentials) => {
  var settings = {
    'clientId':'<id>',
    'scope':'<scope-list>',
    ...
  };

  var body = `client_id=${settings.clientId}&scope=${settings.scope}...`;

  var requestOptions = {
    method: 'POST',
    url: 'https://login.microsoftonline.com/...',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: body
  }

  cy.request(requestOptions);
});
Run Code Online (Sandbox Code Playgroud)

然后,在我的测试中,我有:

context('Home', () => {
  it('Visits Successfully', () => {
    cy.login();

    cy.title().should('include', 'welcome');
  });
});
Run Code Online (Sandbox Code Playgroud)

在测试运行程序中,我看到正在发生登录 POST 请求。我确认正在使用 接收访问令牌console.log,但是,我的标题为空。这就像 Cypress 中未发生 OAuth 之后的重定向一样。但是,当我在浏览器中访问该网站时,重定向会按预期发生。

我缺少什么?

ice*_*bed 4

您可能会忽略实际的 UI 流程和使用第 3 方网站进行 OAuth 的编程流程之间的混淆。

您想要做的是完成编程登录,然后在测试代码中手动将所需的参数发送到应用程序的 OAuth 回调 URL。

这里给出了一个例子(虽然它使用了不同的授权类型,但它给了你一个想法)https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/#Writing-tests-使用 Cypress 登录命令

cypress github 上的另一个问题处理类似的问题 https://github.com/cypress-io/cypress/issues/2085

这也可能有帮助: https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__single-sign-on/cypress/integration/logging-in-single-sign-on -spec.js