javascript - ES6 类的 jest.mock 产生 ReferenceError : require is not defined

标签 javascript jestjs es6-modules

我正在尝试在我的 ES6 javascript 项目中使用 jest 创建一个自动模拟。
我正在使用节点 v15.0.1 , 和 Jest 26.6.0在 ubuntu 上 18.04.5 .
我有一个包含以下代码的测试文件:

import RenderBuffer from './renderbuffer.js'

jest.mock('./renderbuffer.js');

beforeEach(() => {
    RenderBuffer.mockClear();
});
当我运行测试时,我遇到了以下问题:
ReferenceError: require is not defined

      4 | 
      5 | beforeEach(() => {
    > 6 |     RenderBuffer.mockClear();
        |       ^
      7 | });
      8 | 
这个错误让我感到惊讶,因为我没有使用 require 语句。
我的 package.json 配置包含以下内容:
"type": "module",
    "main": "src/index.js",
    "devDependencies": {
        "jest": "^26.5.3",
        "jest-canvas-mock": "^2.3.0"
    },
    "jest": {
        "setupFiles": ["jest-canvas-mock"]
    },
    "scripts": {
        "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
        "test-coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage"
    }
关于这个问题的根本原因是什么的任何想法?

最佳答案

您必须禁用任何源代码转换才能通过设置使其工作

{
  transform: {}
}
在您的 Jest 配置文件中。默认 transform选项配置为使用 babel-jest .请引用this Jest documentation section更多细节。另请注意,您应该导入 jest明确:
import { jest } from '@jest/globals';
不幸的是,正如其他评论者已经提到的那样,它在运行您的测试时仍然可能存在一些问题。可能,应该follow this issue跟踪 Jest 中为 ESM 支持所做的更改。
例如,我当时很不幸地模拟了静态模块导入(版本 26.6.2):

jest.(do|un)mock

Since ESM has different "stages" when evaluating a module, jest.mock will not work for static imports. It can work for dynamic imports though, so I think we just have to be clear in the docs about what it supports and what it doesn't.

jest.mock calls are hoisted, but that doesn't help in ESM. We might consider transforming import 'thing' to import('thing') which should allow hoisting to work, but then it's async. Using top-level await is probably a necessity for such an approach. I also think it's invasive enough to warrant a separate option. Something to discuss - we don't need to support everything jest.mock can for for an initial release.

关于javascript - ES6 类的 jest.mock 产生 ReferenceError : require is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64582674/

相关文章:

javascript - 拦截对构造函数的调用

javascript - JS 游戏编程 - 在 iPad 浏览器中使用蓝牙键盘/iCade 的键盘事件?

javascript - 省略文件扩展名,ES6模块NodeJS

javascript - 为什么这些 Jest 测试失败了?类型错误 : Cannot read property 'apply' of undefined

javascript - 如果需要,如何创建一个可以导入单个组件的库 à la lodash

javascript - 在不明确列出它们的情况下,以其导出名称导入所有命名导出

javascript - React-router hashHistory 推送仅更改 URL

Javascript 设置对象选项

javascript - 开 Jest 安全 cookie?

javascript - 如何模拟内部函数?