gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:38:25 25 4
gpt4 key购买 nike

我正在尝试在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com