0

I am facing issues mocking a method which internally makes call to database to fetch data. Please find the code below:

const getData = async (...args) => {

    // first call
    await db.getData();
    
    // second call
    await db.queryData();
    
    return data;
}

const generateResult = async (...args) => {

    const data = await getData(...args);
    // rest of the code
    
    return result;
}

export ClassTest;

In the test file:

describe(('Verify generateResult') => {

    jest.spyOn(generateResult, 'getData').mockImplementation((...args) => {
        return data;
    });

    it('should return result', async () => {
        const result = await generateResult(..args);
        expect(result).toBeTruthy();
    });
});

The getData method makes database calls to retrieve data. Rest of the code just massages the data and returns result. Even though its been mocked the code fails when the database calls are made. I assume that it should get data from mocked implementation and rest of the code should execute. Not sure what is wrong here. Could anyone pls let me know. Do not have a lot of experience writing jest test cases.

thanks

Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54

2 Answers2

0

Any chance that you could move the getData method to another module? Then you can mock the getData and the imported version would be the mocked one everywhere. Just an idea.

getData.js

export const getData = async (...args) => {
    const data = await Promise.resolve(false);
    console.log('original called')
    return data;
}

dbUtils.js

import { getData } from './getData'

export const generateResult = async (...args) => {
    const data = await getData(...args);
    return data;
}

and the test:

import * as getDataUtils from '../getData';
import { generateResult } from '../dbUtils';

it('should return result', async () => {
    jest.spyOn(getDataUtils, 'getData').mockResolvedValue(true);

    const result = await generateResult();
    expect(result).toBeTruthy();
});
Marek Rozmus
  • 773
  • 7
  • 13
0

A similar question was answered in this post: Jest mock inner function

It would help if you moved the helper function, getData, to a separate module and import that module to generateResult. See below:

helper.js

const getData = async (...args) => {
    await db.getData();
    await db.queryData();
    
    return data;
}

index.js

import * as helper from './helper'

export const generateResult = async (...args) => {
    const data = await helper.getData(...args);
    return data;
}

and the test:

import * as helper from './helper'
import { generateResult } from '../dbUtils';

it('should return result', async () => {
    jest.spyOn(helper, 'getData').mockResolvedValue(true);
    // or 
    helper.getData = jest.fn().mockImplementation(() => true);

    const result = await generateResult();
    expect(result).toBeTruthy();
});
rann
  • 11
  • 2