I want to use jest to mock the method 'sendBatch' from third-party-package: 'messaging-api-messenger' in my unit test.
My code:
// sendMessages.js
async function sendMessage () {
const { MessengerClient } = require('messaging-api-messenger')
const client = new MessengerClient({accessToken: 'accessToken'})
return client.sendBatch([{message:'message', to:'someone'}]
}
module.exports = sendMessage()
// send.test.js
const Send = require('sendMessage')
const sendBatchMock = jest.fn().mockImplementation(() => {})
jest.mock('messaging-api-messenger', () => {
return {
MessengerClient: jest.fn().mockImplementation(() => ({
sendBatch: sendBatchMock
}))
}
})
sendBatchMock.mockReturnValue({
success: true,
responseData: [{ code: 200, body: { } }]
})
it('send message' async () => {
const sendResult = await Send.sendMessage()
expect(sendResult).toEqual('what I want')
}
This is sendBatch actually return:
sendResult {
success: true,
responseData: [ { code: 400, headers: [Array], body: [Object] } ]
}
But I want sendBatch return this:
sendResult {
success: true,
responseData: [ { code: 200, headers: [], body: {} } ]
}
How do I mock sendBatch method which is called at sendMessage.js, and ask sendBatch method return specific values I want and check return values?
This is my solution:
const sinon = require('sinon')
const { MessengerClient } = require('messaging-api-messenger')
sinon.stub(MessengerClient.prototype, 'sendBatch').resolves([{ code: 200, headers: [], body: {} } ])