'how to mock slack web api for jest
i have an app that's using the @slack/web-api
package through the named import WebClient
.
i want to test one of the controllers that uses a model that in turns uses the slack web api.
something like this:
// model.ts
import { WebClient } from '@slack/web-api';
export default (token) => {
const slackWebClient = new WebClient(token);
return {
func: () => slackWebClient.chat.postMessage(...)
}
}
// controller.ts
import model from './model'
export const controller = async () => {
const m = model(token)
await model.func()
}
as for my testing, i tried to mock the package then test the behaviour of the chat.postMessage
function but i keep getting 0 calls despite when adding a console.log right next to it i get an output.
this is my test:
import { controller } from '../controller';
const mSlack = {
chat: {
postMessage: jest.fn(),
},
};
jest.mock('@slack/web-api', () => {
return { WebClient: () => mSlack };
});
it('test controller', async () => {
await controller()
expect(mSlack.chat.postMessage).toHaveBeenCalledTimes(1);
})
this is a simplified version of my code as my code would be very large and i already tested all other aspects and i'm getting the desired responses. my problem is not with the testing itself but with the mock since the tested code is reachable but i'm missing something on how to assert on it.
i'm also using typescript with nodejs for this app.
thanks in advance.
Solution 1:[1]
The problem is that you are testing controller.ts
but @slack/web-api
is imported from model.ts
. even though controller imports model however jest does not mock it. You can only mock libraries which are directly imported in controller.ts
(in this case).
My suggestion is to mock model.ts
itself rather than its dependencies.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | omidh |