Tuesday, January 10, 2023

How to mock specific method mockImplementation jest in nodejs?

 Here is some best solution , how we can mock specific method from utils file.


Step1: I have created a utils.js file and it contains two methods

like :

const getSchoolName = async ({schoolId }) => {


return 'Bikash School';
};
const getAllSchoolList = async ({schoolId }) => {


return {object};
};


Step 2 : create actual-utils-call.test.js  and import the utils.js file

import { getAllSchoolList, getSchoolName } from './util';



jest.mock('./utils', () => {
const originalUtils = jest.requireActual('./utils');
return {
...originalUtils,
getSchoolName: jest.fn(),
};
});


describe('Mock specific mockImplementation', () => {
it('getSchoolName method should mock from util file', async () => {
getSchoolName.mockImplementation(() => {
return 'different School Name';
});
});

// Here you call your actual method where getSchoolName method is invoke

});

No comments:

Post a Comment