javascript - 如何在 Jest 中使用全局变量

标签 javascript jestjs integration-testing

我有我的 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反对并检查您的测试。

密码箱:https://codesandbox.io/s/unruffled-feistel-byfcc

关于javascript - 如何在 Jest 中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426124/

相关文章:

javascript - 我应该在每个渲染器上调用一个函数还是在 React 类组件中使用箭头函数?

javascript - 无法在 'getStartPositionOfChar' 上执行 'SVGTextContentElement'

javascript - expect 中 toContain() 的实际用途是什么?

spring-boot - @DirtiesContext 不适用于@Nested 测试

selenium - 使用带有 127.0.0.1 的内容脚本和带有 Firefox 插件的自定义端口

c# - WebApplicationFactory 抛出 contentRootPath 在 ASP.NET Core 集成测试中不存在的错误

javascript - 单选按钮拦截 Angular/Javascript 中未经检查的事件

Javascript - 动态改变setTimeout/setInterval的间隔值

javascript - componentWillMount 之前的 enzyme 模拟函数

javascript - Jest 异常匹配类型和消息