Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest.fn's implementation argument is no longer optional #32863

Closed
3 tasks done
fgrandel opened this issue Feb 7, 2019 · 4 comments · Fixed by #32864
Closed
3 tasks done

jest.fn's implementation argument is no longer optional #32863

fgrandel opened this issue Feb 7, 2019 · 4 comments · Fixed by #32864

Comments

@fgrandel
Copy link

fgrandel commented Feb 7, 2019

If you know how to fix the issue, make a pull request instead.

This was introduced by PR #31094 / Commit 3b921ef

@antoinebrault
Copy link
Contributor

What is the issue ? Do you have an example ?

current implementation is :

function fn(): Mock;
function fn<T, Y extends any[]>(implementation: (...args: Y) => T): Mock<T, Y>;

@fgrandel
Copy link
Author

fgrandel commented Feb 7, 2019

type PropOf = T[keyof T]
...
mockedMethods.forEach(mockedMethod => mocked[mockedMethod] = jest.fn<PropOf>() as MockFunction<T[keyof T]>)

(This already presumes the PR I just provided)

Before I either had the choice not being able to get proper typing at all or pass jest.fn(undefined as any) into jest.fn

@fgrandel
Copy link
Author

fgrandel commented Feb 7, 2019

Let me give you the full source code - otherwise it will be hard to understand what we're up to...

We have a small utility function that allows us to mock any typescript interface like this:

...
let mockMyInterface: Mocked<MyInterface>
mockMyInterface = mock<MyInterface>('someMethod', 'someOtherMethod')
...
mockMyInterface.someMethod.mockReturnValue('12345')
...

export type MockFunction<F extends GenericFunction> = F & jest.Mock<ReturnType<F>, ArgsType<F>>

export type Mockable<T> = {
  [K in keyof T]: GenericFunction
}

export type Mocked<T extends Mockable<T>> = {
  [K in keyof T]: MockFunction<T[K]>
}

type PropOf<T> = T[keyof T]

export function mock<T extends Mockable<T>>(...mockedMethods: (keyof T)[]): Mocked<T> {
  const mocked: Mocked<T> = {} as Mocked<T>
  mockedMethods.forEach(mockedMethod => mocked[mockedMethod] = jest.fn<PropOf<T>>() as MockFunction<T[keyof T]>)
  return mocked
}```

@antoinebrault
Copy link
Contributor

Ok I understand. Thanks. I'll review the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants