1

I have module that contains several functions (foo, bar, etc).

// moduleA.js

const someModule = require('someModule')


const moduleA = () => {
   const bar = (param1, param2) => {
     // some implementation
   }

   const foo = (params) => {
    // some implementation
    bar(1, 2)
   }

   return Object.assign({}, someModule, {
      foo,
      bar
   })
}

module.exports = moduleA

What I want to do is to mock other module functions (bar) being called within my current test (foo) function.

// jest test file
describe('Testing foo, mocking bar', () => {
    const checker = moduleA()

    it.only('When this, then that', async () => {
        // THIS IS NOT WORKING
        const spy = jest.spyOn(checker, "bar").mockReturnValue("XXXX")


        const response = await checker.foo({ 1, 2, 3})
        expect(response).toBeDefined()
    })
})

What is the correct way to spy or stub the bar function so that I can mock the results and only focus testing the foo functionality?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Gin
  • 21
  • 3
  • The correct way is _not_ to replace `bar` with a test double, it's part of the thing you're supposed to be testing. The fact that `foo` internally calls `bar` is an _implementation detail_ that could be extracted by a subsequent refactor (examples: https://stackoverflow.com/a/66752334/3001761) - test the _behaviour_ you want. Also note `foo` doesn't actually seem to return anything so whatever the implementation of `bar`, real or otherwise, the assertion `.toBeDefined()` will fail. – jonrsharpe Jun 07 '21 at 16:39
  • @jonrsharpe That's a good rule in general. But there are many cases where you can't do this. For instance, a unit test should never ever read from a database or make an HTTP request. Anything that is outside the scope of your unit needs to be mocked even if it is buried in the stack. – Jordan Jun 24 '22 at 20:18
  • @Jordan yes, of course there are going to be interactions that you want to replace with test doubles. But that doesn't mean it's appropriate to put test boundaries _inside_ module boundaries. When you have databases and requests, _extract them_ from the business logic you're unit testing using e.g. repository patterns, to give a collaborator you can mock _without_ breaking encapsulation. – jonrsharpe Jun 24 '22 at 20:24
  • Does this answer your question? [How to mock functions in the same module using Jest?](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) – jonrsharpe Jun 24 '22 at 20:28
  • Specifically https://stackoverflow.com/a/70066090/3001761, not the tide of Max Power answers – jonrsharpe Jun 24 '22 at 20:29

0 Answers0