gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:06:11 28 4
gpt4 key购买 nike

我正在构建一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com