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

使用Egg-Mock+Jest运行单元测试时遇can't get httpRequest before ready错误求助

单元测试报错排查:can't get httpRequest before ready 及 rimraf 断言失败

依赖版本

"egg-mock": "^3.20.0",    
"jest": "^26.4.0",
"egg": "^3.3.3",
"@midwayjs/core": "^3.0.0",

测试文件代码

import mock from 'egg-mock';

describe('some test', () => {
  let app;
  beforeEach(async () => {
    app = mock.app();
    await app.ready();
  })
  afterEach(() => app.close());

  it('should request /api/test', () => {
    const result = app.httpRequest()
      .get('/api/test');

    expect(result.status).toBe(200);
  });
});

执行yarn run test后的报错

some test › should request /api/test

    assert(received)

    Expected value to be equal to:
      true
    Received:
      false

      at fixWinEPERM (node_modules/mz-modules/node_modules/rimraf/rimraf.js:175:5)
      at node_modules/mz-modules/node_modules/rimraf/rimraf.js:149:7

  ● some test › should request /api/test

    can't get httpRequest before ready

      10 |
      11 |   it('should request /api/test', () => {
    > 12 |     const result = app.httpRequest()
         |                        ^
      13 |       .get('/api/test');
      14 |
      15 |     expect(result.status).toBe(200);

      at Object.get (node_modules/egg-mock/lib/app.js:197:36)

问题原因及解决方法

1. can't get httpRequest before ready 错误

测试用例未处理请求的异步逻辑:app.httpRequest()发起请求是异步操作,你直接同步获取result.status时,请求还未完成,触发了内部状态检查判定app未就绪。

修改测试用例为异步函数,用await等待请求完成:

it('should request /api/test', async () => {
  const result = await app.httpRequest()
    .get('/api/test');

  expect(result.status).toBe(200);
});

2. rimraf 断言失败错误

这是Windows系统下常见的文件权限问题,rimraf删除egg-mock生成的临时文件时遇到权限限制。可尝试以下方案:

  • 升级rimraf版本,可通过yarn upgrade rimraf或在package.json中锁定更高版本
  • 确保执行测试时无其他进程占用临时文件
  • 手动清理项目的node_modules/.cache目录或egg-mock的临时文件路径(通常为/tmp/egg-mock类路径)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:05:35