【问题标题】:How to use a Global Variable in Jest如何在 Jest 中使用全局变量
【发布时间】:2019-12-20 13:36:05
【问题描述】:

我的 Yarn package.json 是这样设置的,我在其中创建了一个名为 localPath 的全局变量。

{
  "jest": {
    "globals": {
      "localPath": "Users/alex/Git/mytodolist"
    }
  }
}

然后,在我的一项规范测试中,我运行

console.log(localPath)

但得到这个错误。

ReferenceError: localPath is not defined

      5 | 
    > 6 |   console.log(localPath)

有人知道如何调用你设置的全局变量吗?我只能找到关于创建变量的文章,而不是关于如何调用它的文章。

来源:https://jestjs.io/docs/en/configuration#globals-object

编辑:感谢@slideshowp2 提供以下正确答案。结果我最终不需要使用全局变量,因为您可以在运行时动态获取执行路径。不过,这在未来肯定会有用。

beforeAll(async () => {
  await page.goto('file:///'+process.cwd()+'/index.html')
})

【问题讨论】:

  • 你在jest.config.js中也尝试过吗?
  • 你能在你的测试中试试global.localPath吗?
  • 是的,这行不通。给出同样的错误。
  • 您上面的内容应该可以正常工作,您确定没有任何其他玩笑配置覆盖package.json 中的内容吗?你是如何运行测试规范的?
  • 以上sn-p是我package.json的范围。我正在使用yarn jest test 运行测试。

标签: javascript jestjs integration-testing


【解决方案1】:

它应该工作。这是一个最小的工作示例:

./src/index.js:

export function sum(a, b) {
  return a + b;
}

./src/__tests__/index.spec.js:

import { sum } from "../";

it("should sum", () => {
  // eslint-disable-next-line
  console.log("localPath: ", localPath);
  const actualValue = sum(1, 2);
  expect(actualValue).toBe(3);
});

jest.config.js:

module.exports = {
  preset: "ts-jest/presets/js-with-ts",
  testEnvironment: "node",
  coverageReporters: ["json", "text", "lcov", "clover"],
  testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
  globals: {
    localPath: "Users/alex/Git/mytodolist"
  }
};

单元测试结果:

 PASS  src/__tests__/index.spec.js
  ✓ should sum (4ms)

  console.log src/__tests__/index.spec.js:5
    localPath:  Users/alex/Git/mytodolist

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.233s
Ran all test suites.

如您所见,全局变量localPath 的值已被设置。请打印global 对象并检查您的测试。

代码沙盒:https://codesandbox.io/s/unruffled-feistel-byfcc

【讨论】:

  • 嘿,通过链接可以帮助你
猜你喜欢
  • 2017-03-19
  • 2018-12-15
  • 2021-07-07
  • 1970-01-01
  • 2018-07-12
  • 2012-06-14
  • 2021-05-23
  • 2018-08-26
  • 2012-12-31
相关资源
最近更新 更多