Mock Slack Web Api Jest

Viewed 1782

I have two files, one in which I initialize a slack web API client, and post a message, and test this based on a mocked value:

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({...});
  })
})

The problem is when I run this code I get the following error: TypeError: web_api_1.WebClient is not a constructor

I've tried various different ways including mocking the module, using esModule: true, not defining WebClient. My question is what am I doing wrong?

1 Answers

You didn't mock @slack/web-api package and the WebClient constructor correctly.

Besides, you forgot import the main.ts module.

E.g.

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' });
  });
});

unit test result:

 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
Related