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

标签 typescript puppeteer ts-jest

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

  1. 如何在 puppeteer 中开玩笑地使用全局变量?现在我的 jest.config.js 中有以下内容
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

我做错了什么?

  • 如何通过命令行传递此全局变量?我在 jest 文档中找到了 --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"}'
      

    关于typescript - 如何在 Jest 中使用全局变量并通过 cmd 传递它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67055201/

    相关文章:

    typescript - 当使用enum作为对象时, "Element implicitly has an ' any'类型,因为索引表达式不是类型 'number'”,为什么?

    javascript - 使用 GraphQL 进行 React-Select

    javascript - 如何使用 JS/Puppeteer 上传文件

    javascript - 在 jest globalSetup 中创建连接时找不到 Typeorm 连接 "default"

    react 原生,开 Jest ,ts-jest : ReferenceError: React is not defined

    typescript - "Module not found: Error: Can' 解决 Electron 和 typescript 和 webpack 项目中的 'electron-is-dev'"

    angular - node_modules/ang-jsoneditor/jsoneditor/jsoneditor.component.d.ts(13,9) 中的错误

    javascript - Puppeteer:通过 HTML 属性查找元素

    node.js - 导出声明类型 ResourceType = Lowercase<Protocol.Network.ResourceType>,使用 Puppeteer 和 typescript 构建 nodejs 应用程序时出错

    amazon-web-services - 用于管道测试的 AWS CDK 抓取嵌套堆栈