Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JEST error TypeError: specificMockImpl.apply is not a function

Trying to mock one of the function with callback from api and getting error as TypeError: specificMockImpl.apply is not a function

import { IEnvironmentMap, load } from 'dotenv-extended';
import { getTokensWithAuthCode, sdk } from '../src/connection-manager';

describe('getTokensWithAuthCode function Tests', () => {

    jest.useFakeTimers();
    let boxConfig: IEnvironmentMap;

    beforeAll(() => {
        boxConfig = load({
            errorOnMissing: true,
        });
    });

    it('should reject a promise if there is wrong auth code provided', async () => {

        sdk.getTokensAuthorizationCodeGrant = jest.fn().mockImplementation(boxConfig.BOX_AUTH_CODE, null, cb => {
            cb('Error', null);
        });

        try {
            const tokens = await getTokensWithAuthCode();
        } catch (error) {
            expect(error).toBe('Error');
        }
    });
});

And my function which is trying to test is as follow:

import * as BoxSDK from 'box-node-sdk';
import { IEnvironmentMap, load } from 'dotenv-extended';
import {ITokenInfo} from '../typings/box-node-sdk';

const boxConfig: IEnvironmentMap = load({
    errorOnMissing: true,
});

export const sdk: BoxSDK = new BoxSDK({
    clientID: boxConfig.BOX_CLIENT_ID,
    clientSecret: boxConfig.BOX_CLIENT_SECRET,
});

/**
 * - Use the provided AUTH_CODE to get the tokens (access + refresh)
 * - Handle saving to local file if no external storage is provided.
 */
export async function getTokensWithAuthCode() {

    return new Promise((resolve: (tokenInfo: ITokenInfo) => void, reject: (err: Error) => void) => {

        if (boxConfig.BOX_AUTH_CODE === '') {
            reject(new Error('No Auth Code provided. Please provide auth code as env variable.'));
        }

        sdk.getTokensAuthorizationCodeGrant(boxConfig.BOX_AUTH_CODE, null, (err: Error, tokenInfo: ITokenInfo) => {
            if (err !== null) {
                reject(err);
            }

            resolve(tokenInfo);
        });
    });
}

Is there any other way to mock function in jest? I have read an article https://www.zhubert.com/blog/2017/04/12/testing-with-jest/

like image 417
badal16 Avatar asked Jan 12 '18 17:01

badal16


1 Answers

On this line, rather than pass a function to mockImplementation, you're passing three arguments:

jest.fn().mockImplementation(boxConfig.BOX_AUTH_CODE, null, cb => {
  cb('Error', null);
});

It looks like you might have just missed some braces. Try switching it to:

jest.fn().mockImplementation((boxConfig.BOX_AUTH_CODE, null, cb) => {
  cb('Error', null);
});
like image 103
Tom Avatar answered Oct 25 '22 00:10

Tom