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

如何验证HTTP调用的执行顺序?(基于Nock与Jest框架)

断言Nock模拟HTTP调用的执行顺序

下面是几种可行的方案,帮你验证调用顺序是否符合预期:

方法1:用Nock的Recorder记录完整调用历史

Nock自带的Recorder可以捕获所有请求的详细信息,包括触发顺序:

  • 在测试执行前启动记录,指定以对象形式输出:
nock.recorder.rec({ output_objects: true });
  • 执行你的业务代码后,通过nock.recorder.play()获取调用历史数组,直接断言数组元素的顺序:
// 执行触发请求的业务逻辑
await yourBusinessFunction();

// 获取调用历史
const callHistory = nock.recorder.play();

// 断言请求顺序:比如第一个是GET /users,第二个是POST /orders
expect(callHistory[0].path).toBe('/users');
expect(callHistory[1].path).toBe('/orders');

// 清理记录器
nock.recorder.clear();

方法2:给Nock模拟绑定回调,追踪调用顺序

给每个Nock模拟添加reply的回调函数,在回调里记录调用标记,再断言标记的顺序:

test('请求按指定顺序执行', async () => {
  expect.assertions(2);
  const callSequence = [];

  // 第一个模拟请求
  nock('https://your-api.com')
    .get('/users')
    .reply(200, [], () => {
      callSequence.push('get-users');
      expect(callSequence).toEqual(['get-users']);
    });

  // 第二个模拟请求
  nock('https://your-api.com')
    .post('/orders')
    .reply(201, [], () => {
      callSequence.push('post-orders');
      expect(callSequence).toEqual(['get-users', 'post-orders']);
    });

  // 执行触发请求的代码
  await yourBusinessFunction();
});

方法3:结合Jest内置断言验证调用顺序

如果你的请求是通过封装的HTTP客户端发起的,可以给客户端方法打Mock,配合Nock拦截实际请求,用Jest的toHaveBeenCalledBefore断言顺序:

// 假设你封装的HTTP客户端是httpClient.js
jest.mock('./httpClient');
const httpClient = require('./httpClient');

test('请求顺序符合预期', async () => {
  // 用Nock拦截实际请求
  nock('https://your-api.com').get('/users').reply(200);
  nock('https://your-api.com').post('/orders').reply(201);

  // 执行业务逻辑
  await yourBusinessFunction();

  // 断言get请求先于post请求被调用
  expect(httpClient.get).toHaveBeenCalledBefore(httpClient.post);
});

注意:toHaveBeenCalledBefore需要Jest版本23.0.0及以上支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:47:36