jest.mock(..) 在“描述”中不起作用(类型错误:moduleName.split 不是函数)

Oli*_*ins 2 jestjs jest-fetch-mock

jest.mock(..)似乎不适用于我的测试的“描述”级别。

如果我有以下内容:

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

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

    jest.mock(someFunction);

    test(' snapshot', () => {

    });
});
Run Code Online (Sandbox Code Playgroud)

然后运行“测试”(即在测试级别),工作正常。

但是,如果我运行“描述”(即描述级别或套件级别),则会出现以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

如果我有这个:

describe('Overview Test', () => {
    test(' snapshot', () => {
        jest.mock(someFunction);
    });
});
Run Code Online (Sandbox Code Playgroud)

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

我也试过这个:

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


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

    beforeEach(() => {
        jest.mock(someFunction);
    });

    test(' snapshot', () => {

    });
});
Run Code Online (Sandbox Code Playgroud)

它不起作用。

更新

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

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

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

        jest.mock('./something/someFile', () => {
            return { someFunction: jest.fn(() => "futhissit")};
        });

        test(' snapshot', () => {
            someFunction()
        });
    });
Run Code Online (Sandbox Code Playgroud)

Chr*_*ras 8

开玩笑,mock如果对于模拟模块,第一个参数是moduleName它必须是有效的模块名称(内部node_modules或文件路径)而不是直接的函数/模块:

jest.mock(moduleName, factory, options)

在需要时使用自动模拟版本模拟模块。factory并且options是可选的。

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

当你想测试一个 ES 模块时,你传递模块的位置,然后创建moduleName一个factoryusing__esModule: true然后创建属性,导出的函数被模拟 using jest.fn()

someFile.js出口someFunction

module.exports.someFunction = () => 'Some function result!';
Run Code Online (Sandbox Code Playgroud)

嘲讽someFile.js使用模块jest.mock()

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!');
  });

});
Run Code Online (Sandbox Code Playgroud)

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