运行单元测试时出现'ReferenceError: jest未定义'。

55

我正在开发一个新的应用程序,目前只使用纯JS。我试图在我的Jest单元测试中使用ES6模块,所以我按照2020年更新的指示进行了操作。

然而,在遵循这些指示后,当运行我的单元测试时,我会收到错误ReferenceError:jest未定义

这是我的package.json:

{
  "version": "1.0.0",
  "main": "app.js",
  "type": "module",
  "jest": {
    "testEnvironment": "jest-environment-node",
    "transform": {}
  },
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "start": "node server.js"
  },
  "license": "ISC",
  "devDependencies": {
    "express": "^4.17.1",
    "jest": "^26.6.3",
    "jest-environment-node": "^26.6.2",
    "open": "^7.3.0"
  },
  "dependencies": {}
}

以下是我的测试文件。错误是由jest.fn调用引起的:

import { getTotalNumPeople } from "./app.js";


test("Get total number of people", async () => {
    global.fetch = jest.fn(() => Promise.resolve({
            json: () => Promise.resolve({count: 15})
        })
    )
    
    expect(await getTotalNumPeople()).toBe(15);
});

这是为什么发生的任何想法?我确信问题与我遵循的支持ES6模块的步骤有关。在进行这些更改之前,如果我只是将 getTotalNumPeople 函数粘贴到我的测试文件中,我的测试就可以正常运行。

如果我注释掉对函数的模拟,那么我会得到一个关于fetch未定义的ReferenceError(因为getTotalNumPeople使用了fetch)。所以问题不仅仅是jest未被定义。

我注意到,如果我没有指定jest-environment-node作为我的测试环境,错误会由于在我的测试中引用global.fetch而更改为ReferenceError: global is not defined。只是想提醒一下,以防有所帮助。


也许我漏掉了什么,但我期望你的 package.json 有这样一个脚本:"test": "jest",这样 jest 就可以作为 cli 运行。更多信息请参见:https://jestjs.io/docs/en/getting-started - stealththeninja
@stealththeninja 我原本有那个脚本。但是在按照启用 Jest 的 ES6 模块的说明后,我用 "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" 替换了那个脚本。 - Eric
3个回答

80

33
这导致我运行时出现错误:不要在Jest测试环境之外导入@jest/globals - Slava Fomin II
@SlavaFominII:是的!我也遇到了同样的错误!有没有解决方法? - Anand Vaidya
这是关于编程的内容,需要将其从英语翻译成中文。请仅返回翻译后的文本:这不是完整的解决方案,因为会出现“不要导入@jest/globals”的错误。 - rottitime
你能提供代码让我检查吗? - Rupesh
你能提供代码让我检查吗? - undefined

13

虽然与 Rupesh 的答案基本相同,但是你可以通过将设置文件添加到 jest 配置中来全局公开 jest 而无需在每个测试文件中导入它:

"jest": {
    "setupFiles": [
        "<rootDir>/test-setup.js"
    ]
}

然后将此添加到test-setup.js中:

import { jest } from '@jest/globals';

global.jest = jest;

此外,为了更好地支持jest的ESM模块,需要在package.json文件中添加以下test脚本:

"scripts": {
    "test": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest )"
},

1

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