【问题标题】:Mock Slack Web Api Jest模拟 Slack Web Api Jest
【发布时间】:2021-07-03 14:37:52
【问题描述】:

我有两个文件,其中一个我初始化了一个松弛的 Web API 客户端,然后发布一条消息,并根据一个模拟值对其进行测试:

main.ts:

import { WebClient } from '@slack/web-api';
const slack = new WebClient(process.env.SLACK_API_KEY as string);

slack.chat.postMessage({...});

test.ts

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

beforeAll(async () => {
  slack = new WebClient();
});

jest.mock('@slack/web-api', () => {
  return {
    chat: jest.fn(),
    postMessage: jest.fn(),
  };
});

describe('test', () => {
  it("tests slack message", async () => {
    expect(slack.chat.postMessage).toBeCalledWith({...});
  })
})

问题是当我运行此代码时出现以下错误:TypeError: web_api_1.WebClient is not a constructor

我尝试了各种不同的方法,包括模拟模块,使用esModule: true,而不是定义 WebClient。我的问题是我做错了什么?

【问题讨论】:

    标签: node.js typescript jestjs


    【解决方案1】:

    您没有正确模拟 @slack/web-api 包和 WebClient 构造函数。

    此外,您忘记导入 main.ts 模块。

    例如

    main.ts:

    import { WebClient } from '@slack/web-api';
    const slack = new WebClient(process.env.SLACK_API_KEY as string);
    
    slack.chat.postMessage({
      text: 'Hello world!',
      channel: '123',
    });
    

    main.test.ts:

    import { WebClient } from '@slack/web-api';
    import './main';
    
    jest.mock('@slack/web-api', () => {
      const mSlack = {
        chat: {
          postMessage: jest.fn(),
        },
      };
      return { WebClient: jest.fn(() => mSlack) };
    });
    
    describe('test', () => {
      let slack: WebClient;
      beforeAll(() => {
        slack = new WebClient();
      });
      it('tests slack message', async () => {
        expect(slack.chat.postMessage).toBeCalledWith({ text: 'Hello world!', channel: '123' });
      });
    });
    

    单元测试结果:

     PASS  examples/66991895/main.test.ts (7.253 s)
      test
        ✓ tests slack message (2 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        8.245 s
    

    【讨论】:

    • 啊好吧,问题甚至不是导入 ./main,而是我将聊天和 postMessage 设置为 jest.fn(),而只有 postMessage 是函数,并且其余的是属性。基本上我的设置是错误的。谢谢——非常有帮助
    • 如果我想用 postMessage 的 throw 错误来模拟结果会发生什么
    猜你喜欢
    • 2019-11-29
    • 2019-01-23
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多