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

Jest Mock未捕获Slack Web API请求,求排查方案

问题:Slack Web API Jest Mock未生效,仍调用真实API返回invalid_auth错误

我已经为这个问题折腾了很久,尝试了所有能找到的Slack Web API Jest Mock写法,但都没生效,特来求助排查遗漏点。

我的Jest测试文件结构如下:

import ....(all the imports)

describe('my slack tests', () => {
  beforeAll(() => {
    // Mock slack web api
    jest.mock('@slack/web-api', () => ({
      ...jest.requireActual('@slack/web-api'),
    
      WebClient: jest.fn().mockImplementation(() => ({
        auth: {
          test: () => Promise.resolve({ ok: true }),
        },
        conversations: {
          list: () => Promise.resolve({ ok: true,
                                        response_metadata: {},
                                        channels: [
                                          {name: 'test_channel', id: 'AAABBB123456'}, 
                                          {name: 'ABCD1234', id: 'AAABBB123457'},
                                        ] }),
        },
      })),
    }));
  });
  test('My Test', async () => {
    ...Calling a function that calls the WebClient.conversations.list(...)...
    ... Verified the function works outside the test with proper token....
  });
});

当前报错为Error: An API error occurred: invalid_auth,这说明API请求可能调用了真实的Slack API,Mock根本没捕获到请求。我试了网上所有类似的Mock写法,结果都一样——仿佛完全没配置Mock似的。


排查思路与解决方案

1. 核心问题:jest.mock放置位置错误

Jest的模块Mock是在模块导入阶段生效的,如果你把jest.mock放在beforeAll或其他测试生命周期钩子里面,此时被测试的模块已经导入了真实的@slack/web-api,Mock不会起作用。

修正方法:把jest.mock移到测试文件的顶层作用域,放在所有导入之后、describe之前:

import ....(all the imports)

// 移至顶层,确保模块导入时Mock生效
jest.mock('@slack/web-api', () => ({
  ...jest.requireActual('@slack/web-api'),
  WebClient: jest.fn().mockImplementation(() => ({
    auth: {
      test: () => Promise.resolve({ ok: true }),
    },
    conversations: {
      list: () => Promise.resolve({ 
        ok: true,
        response_metadata: {},
        channels: [
          {name: 'test_channel', id: 'AAABBB123456'}, 
          {name: 'ABCD1234', id: 'AAABBB123457'},
        ] 
      }),
    },
  })),
}));

describe('my slack tests', () => {
  test('My Test', async () => {
    // 调用依赖WebClient.conversations.list的函数
    // 已验证该函数在测试外使用有效token可正常工作
  });
});

2. 验证Mock是否被正确调用

在测试中添加断言,确认Mock的构造函数和方法被调用,排除Mock未触发的情况:

import { WebClient } from '@slack/web-api';

describe('my slack tests', () => {
  test('My Test', async () => {
    // 执行你的测试逻辑
    await yourFunctionThatUsesSlackAPI();

    // 验证WebClient构造函数被调用
    expect(WebClient).toHaveBeenCalled();
    // 获取Mock的客户端实例
    const mockClient = WebClient.mock.instances[0];
    // 验证conversations.list方法被调用
    expect(mockClient.conversations.list).toHaveBeenCalled();
  });
});

3. 其他排查点

  • 确认被测试模块是通过import { WebClient } from '@slack/web-api'导入的,而非动态require或其他绕过模块系统的方式
  • 检查全局Jest配置文件(如jest.config.js)中是否有resetMocks或restoreMocks配置,可能导致Mock被重置
  • 确保被测试代码中没有硬编码真实API请求,或直接绕过WebClient实例发起请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:30:25