You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-scripts test时Mock Promise返回undefined,直接运行Jest正常

React Scripts下Jest Mock Promise返回undefined的问题

我尝试创建一个返回已解析Promise的简单Mock函数,代码如下:

const mockPromise = jest.fn().mockResolvedValue('example');

test('mock promise resolves', async () => {
  const result = await mockPromise();
  expect(result).toStrictEqual('example');
});

直接运行Jest时测试正常通过:

⋙ npx jest src/components/example.test.ts
 PASS  src/components/example.test.ts
  ✓ mock promise resolves (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.305 s
Ran all test suites matching /src\/components\/example.test.ts/i.

但使用react-scripts test运行时测试失败:

⋙ npm t -- src/components/example.test.ts

> frontend@0.1.0 test
> react-scripts test --watchAll=false src/components/example.test.ts

 FAIL  src/components/example.test.ts
  ✕ mock promise resolves (3 ms)

  ● mock promise resolves

    expect(received).toEqual(expected) // deep equality

    Expected: "example"
    Received: undefined

      4 | test('mock promise resolves', async () => {
      5 |   const result = await mockPromise();
> 6 |   expect(result).toEqual('example');
        |                  ^
      7 | });
      8 |

      at Object.<anonymous> (src/components/example.test.ts:6:18)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.93 s, estimated 1 s
Ran all test suites matching /src\/components\/example.test.ts/i.

疑问

为何两种运行方式行为不同?如何让它在react-scripts下正常工作?


原因与解决方案

原因

  1. 版本/配置不一致:Create React App(react-scripts)内置了特定版本的Jest,和全局或项目单独安装的Jest版本可能存在差异,默认配置也有区别,导致mockResolvedValue的处理逻辑不一致。
  2. TypeScript文件后缀影响:测试文件是.ts后缀,但代码使用JS语法,react-scripts的TypeScript编译配置可能对Jest Mock的类型识别有特殊要求,导致mock未正确生效。

解决方案

方案1:统一使用react-scripts的测试命令

放弃直接用npx jest运行测试,始终使用项目的npm test(或yarn test)命令,确保使用Create React App配套的Jest版本和配置,避免版本不兼容问题。

方案2:换用兼容的Mock写法

将mockResolvedValue替换为直接返回已解析Promise的写法,这种写法在不同Jest版本下兼容性更好:

const mockPromise = jest.fn(() => Promise.resolve('example'));

test('mock promise resolves', async () => {
  const result = await mockPromise();
  expect(result).toStrictEqual('example');
});

方案3:调整TypeScript配置(若项目用TS)

如果是TypeScript项目,确保tsconfig.json中包含Jest的类型定义,让TS能正确识别Jest的API:

{
  "compilerOptions": {
    "types": ["jest"]
  }
}

内容的提问来源于stack exchange,提问作者Maddy Guthridge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:42:12