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

Node.js中Jest测试异步函数standup如何正确获取返回值?

问题根源及解决方法

1. 核心问题:standup函数未返回Promise链

你的standup函数内部调用了异步的db_query,但没有返回这条Promise链,导致调用standup()时得到的是undefined,而非可链式调用.then()的Promise对象,所以测试里的data自然是undefined。

2. 修复standup函数

修改函数,让它返回db_query的Promise链:

function standup(userId, client, triggerId) {
  // some calcs
  // 新增return,将Promise链返回出去
  return db_query(key, userId) // 注意参数名:原函数参数是userId,避免写成user_id的笔误
    .then(db_result => {
      return client.views.open({ /* 你的业务数据 */ });
    });
}

3. 正确编写Jest测试(用async/await替代回调)

测试时需要mock两个外部依赖:db_query和client.views.open,避免真实操作数据库或调用框架接口。

示例测试代码:

test('standup 应正确调用client.views.open并返回预期结果', async () => {
  // 1. 定义模拟数据
  const testUserId = 'user_123';
  const testTriggerId = 'trigger_456';
  const mockDbResult = { /* 模拟数据库返回的结果 */ };
  const expectedViewData = { /* 你期望传给client.views.open的参数 */ };
  const mockViewOpenResult = { /* 模拟client.views.open返回的结果 */ };

  // 2. Mock外部依赖
  // Mock db_query,让它返回一个已resolved的Promise
  global.db_query = jest.fn().mockResolvedValue(mockDbResult);
  // Mock client对象,用jest.fn跟踪调用情况
  const mockClient = {
    views: {
      open: jest.fn().mockResolvedValue(mockViewOpenResult)
    }
  };

  // 3. 调用待测试函数(用async/await替代.then,更简洁)
  const result = await standup(testUserId, mockClient, testTriggerId);

  // 4. 断言验证
  expect(result).toEqual(mockViewOpenResult);
  expect(db_query).toHaveBeenCalledWith(/* 填入你代码里的key值, testUserId */);
  expect(mockClient.views.open).toHaveBeenCalledWith(expectedViewData);
});

额外说明

  • 如果client.views.open本身是异步函数(返回Promise),mock时要用mockResolvedValue;如果是同步返回值,用mockReturnValue即可。
  • async/await写法完全规避了回调,同时比.then()更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:17:49