Search code examples
typescripttestingmockingjestjsstub

How to spy on a function used in another function?


I have a file containing source code foo.ts and a test file called foo.test.ts

foo.ts
function bar(argument: arg): boolean {
  return true
}

async function foo(argument: arg) {
  if (bar(argument)) {
    await promiseRequest()
  }
}

I am trying to stub bar() in such a way that when foo(argument) is called that bar() returns false.

I went through the Jest documentation and tried implementing based on the methods there however they do not work when I call foo(argument) in the foo.test.ts file.

How could I do this?


Solution

  • You can use dependency injection for this.

    foo.ts
    
    function bar(argument: arg): boolean {
      return true
    }
        
    async function foo(argument, bar = bar) {
      if (bar(argument)) {
        await promiseRequest()
      }
    }
    
    export const Foo = {
      bar,
      foo
    }
    

    Then in your test file you can mock/stub bar() the following way:

    foo.test.ts
    
    test('Test for foo()', () => {
      const mockBar = jest.fn().mockReturnValue(value)
      expect(Foo.foo(arg, mockBar)).toBe(expectation)
    })