运行单元测试时出现“ReferenceError: jest is not defined”

Eri*_*ric 6 javascript node.js jestjs es6-modules

我正处于一个新应用程序的早期阶段,到目前为止只使用 vanilla JS。我正在尝试将 ES6 模块用于我的 Jest 单元测试,因此我遵循了2020 年更新的说明来实现这一点。

但是,按照这些说明操作后,ReferenceError: jest is not defined运行单元测试时出现错误。

这是我的 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": {}
}
Run Code Online (Sandbox Code Playgroud)

下面是我的测试文件。由于 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);
});
Run Code Online (Sandbox Code Playgroud)

关于为什么会发生这种情况的任何想法?我相信这个问题与我为支持 ES6 模块所遵循的步骤有关。在这些更改之前,当我简单地将getTotalNumPeople函数粘贴到我的测试文件中时,我的测试运行良好。

如果我注释掉嘲笑我的函数,我就会得到一个关于 fetch 未被定义的 ReferenceError (因为getTotalNumPeople使用了 fetch)。所以不仅仅是jest没有定义。

我注意到,如果我不指定jest-environment-node为我的测试环境,错误会更改为ReferenceError: global is not defined由于global.fetch在我的测试中引用。只是想我会注意到,以防万一。

Ian*_*ter 16

虽然本质上与 Rupesh 的答案相同 - 您可以jest全局公开,而无需将其导入每个测试文件 - 通过将安装文件添加到 jest 配置中:

"jest": {
    "setupFiles": [
        "<rootDir>/test-setup.js"
    ]
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到test-setup.js

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

global.jest = jest;
Run Code Online (Sandbox Code Playgroud)

一般来说,ESM 对 jest 的支持是通过testpackage.json 中的脚本改进的,如下所示:

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


小智 13

看起来您没有导入 jest,因此您只需将此行添加到文件顶部:

import {jest} from '@jest/globals'
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅有关 Jest 中对 ES6 模块的本机支持的问题

  • 这给了我一个运行时错误:“不要在 Jest 测试环境之外导入`@jest/globals`” (33认同)