0

I have a module exporting the object of two methods:

  • start()
  • doSomeCheckings()

When start() is called, it calls a doSomeCheckings(). I would like to test that doSomeCheckings() function has been called and eventually returned a mocked value.

I followed up a jest documentation and some duplicated questions here on SO, but it still does not work as I wish. I don't get it what am I missing here ?

Here is the full jest online playground link

// module.js
function start () {
  doSomeCheckings()

  console.log('app started')
}

function doSomeCheckings () {
  console.log('checking')
}

module.exports = { start, doSomeCheckings }

And here is a jest test file:

it('should do some checkings on app start', () => {
  // Given
  const Module = require('./module')

  const spy = jest.spyOn(Module, 'doSomeCheckings')
  spy.mockImplementation(() => console.log('mocked checkings'))

  // When
  Module.start()

  // Then
  expect(spy).toHaveBeenCalled()
})

So instead of console logs in this order:

  1. mocked checkings
  2. app started

I get this:

  1. checkings
  2. app started
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95
  • See https://stackoverflow.com/a/70066090/3001761. You shouldn't and can't mock that as written. – jonrsharpe Dec 13 '22 at 22:04
  • What I've understood, is that my code should be exportable, which it is. I want to understand the concept on how to make feature/functional tests. – aspirinemaga Dec 14 '22 at 04:03

0 Answers0