如何在 Jest 中使用全局变量

pap*_*ppy 8 javascript integration-testing jestjs

我已经package.json像这样设置了Yarn ,在那里我创建了一个名为localPath.

{
  "jest": {
    "globals": {
      "localPath": "Users/alex/Git/mytodolist"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

console.log(localPath)
Run Code Online (Sandbox Code Playgroud)

但得到这个错误。

ReferenceError: localPath is not defined

      5 | 
    > 6 |   console.log(localPath)
Run Code Online (Sandbox Code Playgroud)

有谁知道如何调用您设置的全局变量?我只能找到关于创建变量的文章,但找不到关于如何调用它的文章。

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

编辑:感谢@slideshowp2 下面的正确答案。事实证明,我最终不需要使用全局变量,因为您可以在运行时动态获取执行路径。但是,这在将来肯定会很有用。

{
  "jest": {
    "globals": {
      "localPath": "Users/alex/Git/mytodolist"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 6

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

\n\n

./src/index.js:

\n\n
export function sum(a, b) {\n  return a + b;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
import { sum } from "../";\n\nit("should sum", () => {\n  // eslint-disable-next-line\n  console.log("localPath: ", localPath);\n  const actualValue = sum(1, 2);\n  expect(actualValue).toBe(3);\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

jest.config.js:

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

单元测试结果:

\n\n
 PASS  src/__tests__/index.spec.js\n  \xe2\x9c\x93 should sum (4ms)\n\n  console.log src/__tests__/index.spec.js:5\n    localPath:  Users/alex/Git/mytodolist\n\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        2.233s\nRan all test suites.\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以看到,全局变量的值localPath已经被设置了。请打印该global对象并检查您的测试。

\n\n

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

\n