如何在 Jest 中使用全局变量

How to use a Global Variable in Jest

我已经像这样设置了我的 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')
})

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

./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 对象并检查您的测试。

Codesandbox:https://codesandbox.io/s/unruffled-feistel-byfcc