繁体   English   中英

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

[英]'ReferenceError: jest is not defined' when running unit test

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

但是,按照这些说明操作后,我收到错误ReferenceError: jest is not defined when running my unit test。

这是我的 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 function 粘贴到我的测试文件中时,我的测试运行良好。

如果我注释掉 mocking 我的 function,我就会得到一个关于未定义提取的 ReferenceError(因为getTotalNumPeople使用提取)。 所以这不仅仅是没有定义的jest

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

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

import {jest} from '@jest/globals'

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

虽然与 Rupesh 的答案基本相同 - 您可以全局公开jest而不必将其导入每个测试文件 - 通过将设置文件添加到 jest 配置:

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

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

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

global.jest = jest;

通常,package.json 中的test脚本也改进了 ESM 对 jest 的支持,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM