带有 amplify-js 的赛普拉斯 - ReferenceError:未定义全局

分享于2022年10月08日 amplifyjs angular cypress 问答
【问题标题】:Cypress with amplify-js - ReferenceError: global is not defined带有 amplify-js 的赛普拉斯 - ReferenceError:未定义全局
【发布时间】:2022-10-01 15:56:46
【问题描述】:

我刚刚升级到 Cypress 10,现在收到来自我用来将交互式用户登录到被测站点的 amplify auth 库的问题。我为此做了一个 cy 扩展。

这是 sdk 中的一个已知问题,它使用了这个 global 变量,通过填充它来克服角度问题:

/**
 *  AWS Amplify - Currently, the newest versions of Angular (6+) do not provide the shim for the
 *   global object which was provided in previous versions.
 */
(window as any).global = window;

我已经尝试在 Cypress 10 的许多地方添加它:

  • 在扩展文件中
  • 在赛普拉斯配置文件中
  • 在支持文件中

但没有运气。

FWIW, the gist of the extension

这是完整的堆栈跟踪:

ReferenceError 以下错误源于您的测试代码,而不是 来自赛普拉斯。

全局未定义

当赛普拉斯检测到源自您的测试代码的未捕获错误时 它将自动使当前测试失败。

赛普拉斯无法将此错误与任何特定测试相关联。

我们动态生成了一个新的测试来显示这个失败。看法 堆栈跟踪打印到控制台 在 node_modules/amazon-cognito-identity-js/node_modules/buffer/index.js (http://localhost:4200/__cypress/tests?p=cypress\\support\\e2e.ts:12878:37) 在 __require2 (http://localhost:4200/__cypress/tests?p=cypress\\support\\e2e.ts:17:52) 在 eval (http://localhost:4200/__cypress/tests?p=cypress\\support\\e2e.ts:27843:31) 在 eval (http://localhost:4200/__cypress/tests?p=cypress\\support\\e2e.ts:33508:3) 在 eval () 来自上一个事件: 在 runScriptsFromUrls (http://localhost:4200/__cypress/runner/cypress_runner.js:165206:136) 在 Object.runScripts (http://localhost:4200/__cypress/runner/cypress_runner.js:165221:12) 在 $Cypress.onSpecWindow (http://localhost:4200/__cypress/runner/cypress_runner.js:153378:75)

我试过在扩展文件的顶部添加这个:

let global = {};
(window as any).global = window;

/**
 * amplify-js / cognito auth helper
 * specific personas are logged-in and their tokens are cached to save on round-trips.
 */
import Auth, { CognitoUser } from \'@aws-amplify/auth\';
import Amplify from \'@aws-amplify/core\';

【解决方案1】:

问题在于新的 esbuild 捆绑器,它显然是 WIP,但有些人已经填充了它。

(这一切意味着什么我不知道)

我之前使用新的 npm overrides 指令解决了这个问题:

"overrides": {
    "@aws-amplify/auth": {
      "amazon-cognito-identity-js": {
        "buffer": "6.0.3"
      }
    }
  }

我不喜欢它,因为它现在和将来都有潜在的副作用。

Polyfilling 节点是更好的方法,即 discussed in more detail here ,但简而言之,更新赛普拉斯配置如下:

export default defineConfig({
  e2e: {

    async setupNodeEvents(on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions): Promise {
      // This is required for the preprocessor to be able to generate JSON reports after each run, and more,
      await addCucumberPreprocessorPlugin(on, config);

      const bundler = createBundler({
        plugins: [
          NodeModulesPolyfills(),
          GlobalsPolyfills({
            process: true,
            buffer: true
          }),
          createEsbuildPlugin(config)
        ]
      });

      on('file:preprocessor', bundler);

【讨论】: