5

Say I have the following code:

export const exampleFunc = () => {}

Which is then used in a test like so:

import * as exampleAll from '../../path/to/example'


describe('Example', () => {

  exampleAll.exampleFunc = jest.fn()
})

This fails to typecheck with:

Cannot assign jest.fn() to exampleAll.exampleFunc because property exampleFunc is not writable.

 44│ const mockStore = configureStore([reduxThunk])
 45│
 46│ describe('[Redux action] ExampleAction()', () => {
 47│     exampleAll.exampleFunc = jest.fn()
 48│     beforeEach(() => {
 49│       exampleAll.exampleFunc.mockReturnValue(() => () => {})
 50│     })

Why is it not writable? And how can I do such mocking while also using flow?

Thanks!

Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • I think imports are treated as read only. You could copy the import to another object, `const testExamples = { ...exampleAll, exampleFunc: jest.fn() };` – Dave Meehan Mar 15 '18 at 11:38
  • I tried your solution but it does not solve the problem. The function `exampleFunc` of the `exampleAll` module is not mocked sucessfully – David Schumann Jun 21 '18 at 12:28
  • Did you find a solution? I'm running into the same issue. – Tye2545 Aug 09 '18 at 00:11
  • Ultimately I just stopped typechecking my tests. But I'd love to hear if somebody comes up with a solution! – Abraham P Aug 09 '18 at 07:36
  • Could you spy on the function with `jest.spyOn(exampleAll, 'exampleFunc')`? https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname – user11307804 May 03 '19 at 16:16

0 Answers0