【问题标题】:'ReferenceError: jest is not defined' when running unit test'ReferenceError: jest is not defined' 运行单元测试时
【发布时间】:2021-03-19 06:07:15
【问题描述】:

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

但是,按照这些说明操作后,我在运行单元测试时收到错误 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": {}
}

下面是我的测试文件。由于 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 运行。更多信息:jestjs.io/docs/en/getting-started
  • @stealththeninja 我最初确实有那个脚本。但是在按照使用 Jest 启用 ES6 模块的说明之后,我用 "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" 替换了该脚本

标签: javascript node.js jestjs es6-modules


【解决方案1】:

看起来你没有导入 jest,所以你只需将这一行添加到文件顶部:

import {jest} from '@jest/globals'

有关更多详细信息,请参阅this issue,了解 Jest 中对 ES6 模块的原生支持。

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 2020-08-14
    • 2018-06-04
    • 2021-03-29
    • 2019-12-02
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多