javascript - Cypress 在自定义命令中加载环境变量

标签 javascript environment-variables cypress dotenv

我正在构建一个 Next.js 应用程序并使用 Cypress 编写我的测试。我使用 .env.local file 配置环境变量本地。在 CI 管道中,它们是正常定义的。
我正在尝试在 Cypress 中编写一个自定义命令来加密 cypress/support/command.ts 中的 session .

import { encryptSession } from 'utils/sessions';

Cypress.Commands.add(
  'loginWithCookie',
  ({
    issuer = 'some-issuer',
    publicAddress = 'some-address',
    email = 'some-mail',
  } = {}) => {
    const session = { issuer, publicAddress, email };

    return encryptSession(session).then(token => {
      cy.setCookie('my-session-token', token);
      return session;
    });
  },
);
当这个命令运行时,它会失败,因为 encryptSession使用 TOKEN_SECRET环境变量, Cypress 不加载。
import Iron from '@hapi/iron';

const TOKEN_SECRET = process.env.TOKEN_SECRET || '';

export function encryptSession(session: Record<string, unknown>) {
  return Iron.seal(session, TOKEN_SECRET, Iron.defaults);
}
我如何让 Cypress 从该文件加载环境变量,如果它存在(= 仅在本地,因为变量是在 CI 中定义的 - 它应该正常检测管道中的其他变量,因此相当于检测具有已设置为 export MY_VAR=foo )?

最佳答案

史蒂夫的回答实际上帮助我在 cypress/plugins/index.ts 中得到了这段代码.

import dotenv from 'dotenv';

dotenv.config({ path: '.env.local' });

import { encryptSession } from 'utils/sessions';

/**
 * @type {Cypress.PluginConfig}
 */
const pluginConfig: Cypress.PluginConfig = (on, config) => {
  on('task', {
    encryptSession: (session: {
      issuer: string;
      publicAddress: string;
      email: string;
    }) => encryptSession(session),
  });
};

export default pluginConfig;
然后在 cypress/support/commands.ts .

Cypress.Commands.add(
  'loginWithCookie',
  ({
    issuer = 'some-issuer',
    publicAddress = 'some-address',
    email = 'some-email',
  } = {}) => {
    const session = { issuer, publicAddress, email };

    return cy.task<string>('encryptSession', session).then(token => {
      return cy.setCookie('my-secret-token', token).then(() => {
        return session;
      });
    });
  },
);

关于javascript - Cypress 在自定义命令中加载环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66081413/

相关文章:

linux - 在/etc/environment文件中设置环境变量,值为 "#"字符

python - 在云函数中获取环境变量

cypress - 当域不同时,如何将 Cypress 中的变量从一个测试(它)共享到另一个测试?

javascript - Cypress 无法识别我从/cypress 目录外部导入的模块

JavaScript:s/数字/""x 该数字/g

javascript - 在外部点击时禁用关闭模式

javascript - 如何在 FullCalendar V4 和 Vue.js 中向事件删除按钮添加删除功能

javascript - 如何返回选中复选框的所有值?

python - 将*多个*路径附加到fish中的PYTHONPATH

unit-testing - Cypress 利用 Gitlab 变量