如何在 Jest 中使用全局变量并通过 cmd 传递它

How use global variable in Jest and pass it through cmd

我正在尝试通过 puppeteer 和 jest 创建一些 e2e 测试,但现在我遇到了有关全局变量的问题。所以我有 2 个问题:

  1. 如何在玩偶操作时使用全局变量?现在我的 jest.config.js
  2. 中有以下内容
module.exports = {
    globals: {
        URL: "https://demoqa.com/",
        value: "myvalue"
      },
    preset: 'jest-puppeteer',
    testMatch: ["**/?(*.)+(spec|test).[t]s"],
    testPathIgnorePatterns: ['/node_modules/', 'dist'],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    transform: {
        "^.+\.ts?$": "ts-jest"
    },
    globalSetup: './jest.global-setup.ts',
    globalTeardown: './jest.global-teardown.ts',
    verbose: true
};

然后我尝试在 src/tests/test.spec.ts 中使用全局变量,如下所示:

console.log(URL.toString());
console.log(value.toString());

但这给出了错误,即 value 未定义,但 URL 具有正确的值,如 jest.config.js

我做错了什么?

  1. 如何通过命令行传递这个全局变量?我在 jest docs 中找到了 --globals 标志,并尝试像这样使用它:

npm run jest -- --globals URL='someUrl', value='someValue'

但它也不起作用。

  1. 使用 global 对象(例如 global.value)访问测试中的全局变量

    console.log(global.value);
    
  2. 使用 --globals 参数覆盖有效 JSON 格式的全局变量

    npm run jest -- --globals='{"URL": "someUrl", "value": "someValue"}'