I have a module that looks like follows:
calculate-average.js
const fetch = require('node-fetch') const stats = require('stats-lite') const BASE_URL = 'https://www.example.com/api' const calculateAverage = async(numApiCalls) => { const importantData = [] for (let i = 0; i < numApiCalls; i++) { const url = `${BASE_URL}/${i}` // will make requests to https://www.example.com/api/0, https://www.example.com/api/1 and so on.... const res = await fetch(url) const jsonRes = await res.json() importantData.push(jsonRes.importantData) } return stats.mean(importantData) } module.exports = calculateAverage
I tried testing it along the following lines but I am clearly way off from the solution:
calculate-average.test.js
const calculateAverage = require('../calculate-average') jest.mock( 'node-fetch', () => { return jest.fn(() => {}) } ) test('Should calculate stats for liquidation open interest delatas', async() => { const stats = await calculateAverage(100) // Should make 100 API calls. console.log(stats) })
What I need to do is the following:
- Be able to specify custom varied responses for each API call. For example, I should be able to specify that a call to
https://www.example.com/api/0returns{ importantData: 0 }, a call tohttps://www.example.com/api/1returns{ importantData: 1 }and so on... - If a request is made to a
urlthat I have not specified a response for, a default response is provided. For example if a response is made tohttps://www.example.com/api/101, then a default response of{ importantData: 1000 }is sent.
I would preferably like to do this only using Jest without depending on modules like mock-fetch and jest-mock-fetch. However, if the solution without using is way too complex, then I would be happy to use them. Just don't want to create unnecessary dependencies if not required.