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

Adds mocked test helper for jest.mock typings #774

Merged
merged 4 commits into from Sep 28, 2018

Conversation

huafu
Copy link
Collaborator

@huafu huafu commented Sep 28, 2018

inlined doc:

The mocked test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source. It make use of the latest TypeScript features so you even have argument types completion in the IDE (as opposed to jest.MockInstance).

Note: while it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value.

Example

// foo.ts
export const foo = {
  a : {
    b: {
      c: {
        hello: (name: string) => `Hello, ${name}`,
      },
    },
  },
  name: () => 'foo',
}
// foo.spec.ts
import { mocked } from 'ts-jest'
import { foo } from './foo'
jest.mock('./foo')

// here the whole foo var is mocked deeply
const mockedFoo = mocked(foo, true)

test('deep', () => {
  // there will be no TS error here, and you'll have completion in modern IDEs
  mockedFoo.a.b.c.hello('me')
  // same here
  expect(mockedFoo.a.b.c.hello.mock.calls).toHaveLength(1)
})

test('direct', () => {
  foo.name()
  // here only foo.name is mocked (or its methods if it's an object)
  expect(mocked(foo.name).mock.calls).toHaveLength(1)
})

Closes #576

The `jest.mock()` does not change the type of the exported values from a
module. So we have to:
```ts
expect((foo as any).mock.calls[0][0]).toBe('foo')
```
Now with the `mocked` helper it is possible to do:
```ts
expect(mocked(foo).mock.calls[0][0]).toBe('foo')
```
It is also possible to deeply mock a module right after importing it.
Docs will be updated with related details.

Closes kulshekhar#576
@huafu huafu added this to the 23.10.3 milestone Sep 28, 2018
@coveralls
Copy link

coveralls commented Sep 28, 2018

Pull Request Test Coverage Report for Build 1933

  • 3 of 3 (100.0%) changed or added relevant lines in 2 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.03%) to 91.458%

Totals Coverage Status
Change from base Build 1929: -0.03%
Covered Lines: 1029
Relevant Lines: 1076

💛 - Coveralls

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

Successfully merging this pull request may close these issues.

None yet

3 participants