0

Consider this set of code snippets where I want to write unit tests for function A, which internally calls function B during execution. Assume B is a set of API calls for validation that I want to mock return value to true.

But this spyOn method approach does not work, and the API calls in B still get executed. I've seen approaches with mocking the complete module with jest.requireActual(), but they do not seem to work too.

What could be a better way to test such functions without changing a lot in the codebase index.ts?

//index.ts

async function A (a:string, b:string, c:string) {
// code 
 await B(data);
// code
}

async function B (data:customType) {
  //code 
  //API calls
  //code 
}

export default {
A,
B }

//index.test.ts

import index from '../index.ts'; 

describe('Test suit', ()=>{

  it('should be a test for function A', async ()=> {
    
    jest.spyOn(index, 'B').mockReturnValue(true); 
    // code 
    const result = await index.A('a','b','c');
    // code
  })
})
Piyush Raut
  • 109
  • 1
  • 5

1 Answers1

0

There is not really a good way to do it, when the functions are in the same module with jest only.

But you can with Rewire, it's explained in this answer and worked very well in a similar situation for me: https://stackoverflow.com/a/52725067/16068019

Otherwise if it's an option you could move one of your functions to a different module, but that's not always an option.

leonbubova
  • 109
  • 1
  • 4