Rahul
Rahul

Reputation: 1110

Unit Testing the promises in JEST

The issue is regarding the unit testing using JEST. How to test the a function X which is returning a promise which is making an async HTTP request.

Function X

import httpHelper from './httpHelper';    

function fetchMoxtraAccessToken(userEWAToken, successCallback, failureCallback) {
        const httpObj = {
            url: '/getAccessToken',
            headers: { Authorization: userEWAToken },
        };

        return httpHelper(httpObj, successCallback, failureCallback);
    }

How to unit test the function X on the basis of the response?

Upvotes: 0

Views: 333

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 111062

The easiest way is to mock httpHelper so it just returns a spy on which you can test that is was called with the correct parameter:

jest.mock('./httpHelper', () = > jest.fn()) //Path must be relative to test file
import httpHelper from './httpHelper'

describe(('fetchMoxtraAccessToken') => {
    it(('makes correct http request') => {
        const userEWAToken = 'someUserEWAToken'
        const successCallback = jest.fn()
        const failureCallback = jest.fn()
        fetchMoxtraAccessToken(userEWAToken, successCallback, failureCallback)
        expect(httpHelper).toHaveBeenCalledWith({
            url: '/getAccessToken',
            headers: {
                Authorization: 'someUserEWAToken'
            },
        }, successCallback, failureCallback)
    })
})

Upvotes: 1

Related Questions