简体   繁体   English

问题 mocking 一种使用玩笑进行数据库调用的方法

[英]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.我面临问题 mocking 一种在内部调用数据库以获取数据的方法。 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. getData 方法进行数据库调用以检索数据。 Rest of the code just massages the data and returns result.代码的Rest只是对数据进行按摩并返回结果。 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.我假设它应该从模拟实现中获取数据,并且代码的 rest 应该执行。 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?您是否有机会将getData方法移动到另一个模块? Then you can mock the getData and the imported version would be the mocked one everywhere.然后你可以模拟getData并且导入的版本将在任何地方都是模拟的。 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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