Pablo
Pablo

Reputation: 29519

How to mock only one exported function in jest?

I am trying to mock a single function in my test inside a module. This is the module, where I need to mock only generateServerSeed

// seeds.js
const crypto = require('crypto');

const generateServerSeed = function () {
    return crypto.randomBytes(4).toString('base64');
};

const hashServerSeed = function (serverSeed) {
    const hash = crypto.createHash('sha512');
    hash.update(serverSeed);
    return hash.digest('hex');
};

module.exports = {
    hashServerSeed,
    generateServerSeed
};

This is the function, where this module is used:

// blabla.js
import { generateServerSeed, hashServerSeed } from './seeds';

const VeryImportantFunction = () => {
    const serverSeed = generateServerSeed();
    const hash = hashServerSeed(serverSeed);
    return hash;
};

module.exports = {
    VeryImportantFunction
};

and this is my test file

jest.mock('../seeds');
import { VeryImportantFunction } from '../blabla';
import { generateServerSeed } from '../seeds';
const { hashServerSeed } = jest.requireActual('../seeds');

describe('Playground', function () {
    test('blabla', () => {
        generateServerSeed.mockReturnValue('1234567890ABCDEF');
        expect(VeryImportantFunction()).toBe('f456e02c19ac920...c630bd36cf04b4f57');
    });
});

Above I've tried to mock generateServerSeed, which is ok. But I was not able to find how to leave the original implementation of hashServerSeed using jest.requireActual, because in the test function itself I am not explicitly calling that function.

How can I leave hashServerSeed's original implementation and mock only generateServerSeed while NOT separating these 2 functions and not using manual mock to keep in simple.

Upvotes: 3

Views: 6856

Answers (1)

mgarcia
mgarcia

Reputation: 6335

You can indeed mock the generateServerSeed method and leave all the original remaining methods of seeds using jest requireActual:

import { VeryImportantFunction } from '../blabla';
import { generateServerSeed } from '../seeds';

jest.mock('../seeds', () => {
    // The mock returned only mocks the generateServerSeed method.
    const actual = jest.requireActual('../seeds');

    return {
        ...actual,
        generateServerSeed: jest.fn()
    };
});

describe('Playground', function () {
    test('blabla', () => {
        // Mock the return value.
        generateServerSeed.mockReturnValue('1234567890ABCDEF');

        expect(VeryImportantFunction()).toBe('f456e02c19ac920...c630bd36cf04b4f57');
    });
});

Upvotes: 5

Related Questions