jest.mock(..) 在 'describe' 中不起作用(类型错误:moduleName.split 不是一个函数)



jest.mock(..(在我的测试中似乎无法达到">description"级别。

如果我有以下内容:

import React from 'react';
import {someFunction} from "./something/someFile";
describe('Overview Test', () => {
jest.mock(someFunction);
test(' snapshot', () => {
});
});

然后运行"测试"(即在测试级别(,效果良好。

但是,如果我运行"描述"(即描述级别或套件级别(,那么我会得到以下错误:

TypeError: moduleName.split is not a function
at Resolver.resolveModuleFromDirIfExists (A:frontendnode_modulesjest-resolvebuildindex.js:224:30)
at Resolver.resolveModule (A:frontendnode_modulesjest-resolvebuildindex.js:252:12)

如果我有这个:

describe('Overview Test', () => {
test(' snapshot', () => {
jest.mock(someFunction);
});
});

那么这两种方式都不起作用。

我也试过这个:

import React from 'react';
import {someFunction} from "./something/someFile";

describe('Overview Test', () => {
beforeEach(() => {
jest.mock(someFunction);
});
test(' snapshot', () => {
});
});

但它不起作用。

更新

我也尝试过这个,但它不起作用:

import React from 'react';
import {someFunction} from "./something/someFile";
describe('Overview Test', () => {
jest.mock('./something/someFile', () => {
return { someFunction: jest.fn(() => "futhissit")};
});
test(' snapshot', () => {
someFunction()
});
});

Jestmock用于模拟模块,第一个参数是moduleName,它必须是有效的模块名称(node_modules内部的或文件路径(,而不是直接的函数/模块:

jest.mock(moduleName, factory, options)

当模块需要时,使用自动模拟版本对其进行模拟。5和CCD_ 6是可选的。

您得到TypeError: moduleName.split is not a function的错误是因为resolveModuleFromDirIfExists试图拆分模块名称/路径,您可以在jest-resolve/src/index.ts的第207行看到它。

当您想要测试ES模块时,您可以传递moduleName的模块位置,并使用__esModule: true创建factory,然后使用jest.fn()创建导出函数的属性:

someFile.js导出someFunction:

module.exports.someFunction = () => 'Some function result!';

jest.mock()模拟someFile.js模块

describe('Overview Test', () => {
// Mock the module and its functions
jest.mock('./someFile', () => ({
__esModule: true,
someFunction: jest.fn(() => 'Mocked someFunction!')
}));
// Import the function from the mocked module
const { someFunction } = require('./someFile');
test('snapshot', () => {
// Execute the mocked function
const someResult = someFunction();
// Expect to return the mocked value
expect(someResult).toBe('Mocked someFunction!');
});
});

您必须在jest.mock模块模拟之后导入模拟模块。您可以创建一个jest.setup.js,并使用setupFilesAfterEnv进行配置,CCD_21可以在其中包含您的mock,然后像往常一样在测试文件顶部导入模块。

最新更新