如何在Jest中使用全局变量

8

我已经设置了我的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 中尝试过相同的操作吗? - Matvii Hodovaniuk
你能在测试中尝试使用 global.localPath 吗? - Matvii Hodovaniuk
对,那不起作用。会给出相同的错误。 - alex
你上面的代码应该是可以正常工作的,你确定没有其他的jest配置覆盖了package.json中的配置吗?另外你是怎么运行测试用例的呢? - Tunmee
以上代码片段是我的 package.json 的全部内容。我使用 yarn jest test 运行测试。 - alex
1个回答

6

这应该是可行的。以下是一个最小化的工作范例:

./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对象并进行检查。

嘿,通过这个链接可能会对你有所帮助。 - LDS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接