-1

I'm using jest to test code in a nodejs server. I'm trying to figure out the best way to write the code for integration tests. It seems like jest's mock function necessitates that any sub-function that a function uses should be passed in as a callback.

For example:


async function apiFunction(){
  return await apiCall();
};

async function subFunction1(){
  return await apiFunction();
};

mainFunction(){
  return await subFunction1();
};

Would be better written as:


async function apiFunction(){
  return await apiCall();
};

async function subFunction1(apiFunctionAsCallback){ // all sub-functions passed as a callback
  return await apiFunctionAsCallback();
};

mainFunction(){
  return await subFunction1(apiFunction); // passed as a callback
};

Is this generally a better practice for all code? Only I've not seen this pattern much previously and I'm wondering if there are alternative testing packages to jest that handle this differently?

JimmyTheCode
  • 3,783
  • 7
  • 29
  • 71
  • 1
    Are you trying to ask https://stackoverflow.com/q/45111198/3001761? I would (and [did](https://stackoverflow.com/a/70066090/3001761)) recommend: don't, particularly if you're calling these _integration_ tests. – jonrsharpe Jun 15 '22 at 10:03
  • Yeah that actually answers it, thanks very much! – JimmyTheCode Jun 15 '22 at 12:49

1 Answers1

0

As per @jonrsharpe's guidance, this answer advises the issue can be solved by exporting the sub-function and then mocking it via jest's mocking modules feature. There's a good example in the answer.

JimmyTheCode
  • 3,783
  • 7
  • 29
  • 71