0

In the same test file, I need to test the actual redux action creator and then, later, if the same action creator was called from another function.

If I jest.mock I'm unable to test the actual. If I don't, I can't mock it later. I've also tried jest.spyOn with mockImplementation but it doesn't seem to mock it.

// actionsOne.js
export const myActionOne = ({
  type: 'MY_ACTION_ONE'
})

// test.js
import { dispatch } from './reduxStore.js'
import { myActionOne } from './actionsOne.js'
import { myActionTwo } from './actionsTwo.js'

jest.mock('./actionsOne.js', () => ({
  myActionOne: jest.fn()
}))

test('expectation 1', () => {
  // would pass if no mocking is in place. fail otherwise.
  expect(dispatch(myActionOne())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})

test('expectation 2', () => {
  dispatch(myActionTwo()) // say this would also dispatch myActionOne somewhere
  // would pass if mocking is in place. fail otherwise.
  expect(myActionOne).toHaveBeenCalled()
})

Because myActionOne does a lot of stuff when dispatched, I wanted to test it once and for myActionTwo just check if it was called.

Any recommendation? Thanks!

fdelafuente
  • 1,114
  • 1
  • 13
  • 24
AlvMF1
  • 150
  • 1
  • 2
  • 11
  • Possible duplicate of [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) – Valerii May 28 '19 at 20:53

1 Answers1

0

Ok, I got it to work using jest.requireActual():

test('expectation 1', () => {
  const { myActionOne: myActionOneActual } = jest.requireActual('./actionsOne.js')

  expect(dispatch(myActionOneActual())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})

expectation 1 passes because we are asserting with the actual function.

No changes to expectation 2, since it asserts with the mocked function.

AlvMF1
  • 150
  • 1
  • 2
  • 11