gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:48:02 24 4
gpt4 key购买 nike

我有我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com