NodeJS Cypress -在测试中间从插件文件重新运行配置

dxpyg8gm  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(131)

我有一个问题,我需要在测试中重新运行配置,因为我们使用的角色只有一个小时的权限。您甚至不能扩展角色权限,因为我们在使用此角色时进行角色链接。有人遇到过这个问题吗?我的问题是,当测试失败或测试在凭据过期后运行时,如何在cypress/plugins/index.js中重新运行代码以获得新的凭据?
Plugin/index.ts

import * as secretsManager from '@amzn/cypress-midway-plugin/secret_manager';
import PluginEvents = Cypress.PluginEvents;
import PluginConfigOptions = Cypress.PluginConfigOptions;
import * as AWS from 'aws-sdk'

import { CYPRESS_PRINCIPAL, CYPRESS_SECRET_ID, REGION, STAGE } from '../resources/constants';
import fetchSigv4Session from "./sigv4";
import getEnvVariables from "./env-variables";

/**
 * @type {Cypress.PluginConfig}
 */

export default async (on: PluginEvents, config: PluginConfigOptions): Promise<PluginConfigOptions> => {  // `on` is used to hook into various events Cypress emits
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  // assuming running from Hydra

  on('task', {
    log (message) {
      console.log(message)
      return null
    }
  })

  config.env.SIGV4_SESSION = await fetchSigv4Session(AWS);

  config.env.REGION = REGION;
  config.env.CYPRESS_ENV_VARIABLES = getEnvVariables(STAGE)

  on('after:run', () => {
    console.log("Test finished at: ", new Date())
  });

  return config;
};

Support/index.ts

// Import commands.js using ES2015 syntax:
import AWS = require('aws-sdk');
import fetchSigv4Session from '../plugins/sigv4';
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')

const CYPRESS_LOG_NAME = 'Login with Midway';

Cypress.on('uncaught:exception', (err, runnable) => {
  // returning false here prevents Cypress from
  // failing the test
  console.warn('Uncaught exception (suppressed):', err);
  return false;
});

//Runs at start of each test suites
before(() => {
  
    cy.log("Starting Authentication")
    cy.setCookie('region', Cypress.env('REGION'));
    cy.setCookie('session', Cypress.env('SIGV4_SESSION'));
    

    const preserve = [
      'session',
      'cypress',
      'region'
    ];
    Cypress.Cookies.defaults({ preserve });

    return cy.request({
      url: `https://authentication.api.com/api/session-status`,
      method: 'GET',
      headers: {'Clear-Site-Data': "*"} //This will allow us to do a fresh call rather than using browser's cache
    }, ).then(async response => {
      Cypress.log({
        name: CYPRESS_LOG_NAME, message: [`Logged in and running cypress tests.`]
      });
      cy.wrap(response, {log: false});
    })
});

所以,当我遇到这个问题时,我需要获得一个新的凭证,如果我在测试之间或在Cypress失败事件处理程序中这样做,它不会识别任何节点环境变量。不确定是否有任何其他钩子可以调用以使在plugins/index.ts中运行代码的环境正常运行

apeeds0o

apeeds0o1#

在测试中更改配置的方法是使用Cypress.config(configKey, newConfigValue)
但是Cypress有固定的配置键,所以对于凭证,你可能使用环境变量,这是一个类似的语法:Cypress.env(envKey, newEnvValue)
这可以用于任何键,而不仅仅是Cypress定义的键。
管理凭据的正确方法是使用cy.session()命令。比如说

// Caching session when logging in via API
cy.session(username, () => {
  cy.request({
    method: 'POST',
    url: '/login',
    body: { username, password },
  }).then(({ body }) => {
    window.localStorage.setItem('authToken', body.token)
  })
})

然后,您可以通过使用不同的username调用cy.session()来更改凭据。
以下是进一步阅读的参考:Session

z9ju0rcb

z9ju0rcb2#

如果您需要在Cypress的测试过程中重新运行配置,特别是在cypress/plugins/index.js文件中,您可以使用Cypress事件系统来实现这一点。事件系统允许您侦听特定事件并相应地执行代码。
要处理测试失败或凭据过期的场景,可以利用afterEach事件。此事件在每个单独的测试用例之后触发,而不管它是通过还是失败。您可以在cypress/plugins/index.js文件中添加此事件的侦听器,并执行必要的代码来刷新凭据。
此链接可能有助于相应地组织您的测试。https://filiphric.com/cypress-basics-before-beforeeach-after-aftereach

// cypress/plugins/index.js

  module.exports = (on, config) => {
// Refresh credentials function
 const refreshCredentials = () => {
// Your code to refresh the credentials goes here
// This can include requesting new credentials or generating new ones
};

// After each test case
on('afterEach', (test, runnable) => {
if (test.state === 'failed') {
  // If the test fails, refresh the credentials
  refreshCredentials();
}
});

// Return the updated configuration
return config;
 };

相关问题