DEV Community

Discussion on: The only 3 steps you need to mock an API call in Jest

Collapse
 
supriya_nakerikanti_5dc8a profile image
Supriya Nakerikanti

Hi Zak, This is very helpful. I am having a bit of trouble with this.

If a method is expecting the endpoint as one of its params, then how do i mock it and test the method?

test('test callAPI method', async () => {
jest.mock('axios');
axios.get.mockResolvedValue({
body: {
category: "2",
pinNo: "A-12-345-67",
pinValidity: "Valid",
planType: "Y",
relationShip: "D - Grandparent"
},
status: 200
});

const result = await callAPI();

const expected = {
    body: {
        category: "2",
        pinNo: "A-12-345-67",
        pinValidity: "Valid",
        planType: "Y",
        relationShip: "D - Grandparent"
    },
    status: 200
}

expect(result).toEqual(expected)
Enter fullscreen mode Exit fullscreen mode

});

I tried doing this and i am receiving the following error. I am trying to see if you could help me with this. Thanks in advance !

Error -

_axios.default.get.mockResolvedValue is not a function
TypeError: _axios.default.get.mockResolvedValue is not a function
at Object. (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/apps/na-showroom/src/utils/BudgetFilterPaymentOperations/BudgetFilterPaymentOperations.test.js:419:12)
at Promise.then.completed (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/utils.js:276:28)
at new Promise ()
at callAsyncCircusFn (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/utils.js:216:10)
at _callCircusTest (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/run.js:212:40)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at _runTest (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/run.js:149:3)
at _runTestsForDescribeBlock (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/run.js:63:9)
at run (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/run.js:25:3)
at runAndTransformResultsToJestFormat (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:176:21)
at jestAdapter (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:109:19)
at runTestInternal (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-runner/build/runTest.js:380:16)
at runTest (/Users/lnakerik/Desktop/eCommerce-showroom/showroom-web/ui.showroom/node_modules/jest-runner/build/runTest.js:472:34)