jest.mock(..) not working in 'describe' (TypeError: moduleName.split is not a function)

jest.mock(..) not working in 'describe' (TypeError: moduleName.split is not a function)

jest.mock(..) 在我的测试中似乎无法在“describe”级别工作。

如果我有以下情况:

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

describe('Overview Test', () => {

    jest.mock(someFunction);

    test(' snapshot', () => {

    });
});

然后 运行 宁 'test' (即在测试级别),工作正常。

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

TypeError: moduleName.split is not a function

    at Resolver.resolveModuleFromDirIfExists (A:\frontend\node_modules\jest-resolve\build\index.js:224:30)
    at Resolver.resolveModule (A:\frontend\node_modules\jest-resolve\build\index.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()
        });
    });

Jest mock 如果用于模拟模块并且第一个参数是 moduleName 它必须是有效的模块名称(inside node_modules 或文件路径) 而不是直接的 function/module:

jest.mock(moduleName, factory, options)

Mocks a module with an auto-mocked version when it is being required. factory and options are optional.

您得到的错误 TypeError: moduleName.split is not a function 是因为 resolveModuleFromDirIfExists tries to split the module name/path and you can see it inside 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 配置它,它可以在其中包含您的模拟,然后像正常一样在测试文件的顶部导入模块。