jest.mock should override original flow types

Created on 26 Jul 2017  路  4Comments  路  Source: facebook/jest


Do you want to request a feature or report a bug?: bug

What is the current behavior?

When using jest.mock, Flow doesn't understand that the imported and mocked file is different from the original import.

If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install and yarn test.

import {fn} from './file.js'

jest.mock('./file.js', () => {
  return {
    fn: jest.fn(() => {}),
  }
})

// $FlowError: property `mockClear`: Property not found in statics of function
fn.mockClear()

What is the expected behavior?
Somehow either flow or Jest flow typing should be able to override the original types.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.
jest: 20.0.4
flow-bin: 0.50

Enhancement

Most helpful comment

we'll be redesigning our mock system to be more compatible with flow.
Most likely it'll look something like

impart {fn} from './file.js';
jest.mock.clear(fn);

so we don't magically mutate/patch any objects in runtime, but rather provide a separate API to extract this information from mocked functions

All 4 comments

we'll be redesigning our mock system to be more compatible with flow.
Most likely it'll look something like

impart {fn} from './file.js';
jest.mock.clear(fn);

so we don't magically mutate/patch any objects in runtime, but rather provide a separate API to extract this information from mocked functions

@joeybaker one of the workarounds is to do something like:
(fn: any).mockClear()

I think I found the most suitable solution (or rather, my colleague suggested it to me):

let mockFn: JestMockFn<[], object>
jest.mock('./file.js', () => {
  mockFn = jest.fn(() => {})
  return {
    fn: mockFn,
  }
})

mockFn.mockClear()
Was this page helpful?
0 / 5 - 0 ratings