简体   繁体   中英

issue with mocking a method which makes database calls using jest

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM