Ts-jest: Feature req: Add static functions for mock functions.

Created on 5 Aug 2018  路  4Comments  路  Source: kulshekhar/ts-jest

Issue :

When mocking module by jest.mock(), I would like to use jest.fn() to mock functions of the module.

jest.mock("../src/dependency", () => {
  return {
    dependencyFunc: jest.fn()
  };
});

Latter in the actual tests, I need to implement different behavior for the functions.

dependencyFunc.mockImplementation(() => {
  return "modified mock implementation";
});

The mock functions works fine with JS. But in TypeScript, with dependencyFunc has no defined mockImplementation, the IDE(vscode) shows error

[ts] Property 'mockImplementation' does not exist on type '(input: string) => string'.

The test can still run successfully. But I think it would be better to have some global functions to do the implement. Likes when in mockito.

Expected behavior :

I would suggest to add global/static functions for mock functions. Something could be used like:

jest.mockFn.mockImplementation(dependencyFunc, () => {
  return "modified mock implementation";
});

Output from debug log :

# content of debug.txt :

none

Minimal repo :

https://github.com/TKJohn/ut-ts-jest
https://github.com/TKJohn/ut-ts-jest/blob/master/test/dependent-modify.spec.ts

Most helpful comment

Found out #576. And it is a good hint to use type case to deal with type issus.
I'll close this one. Thanks a lot for help.

All 4 comments

Thanks @TKJohn. The easiest workaround is to put you jest.mock('xxx') call before the actual import ... from 'xxx' in your test file.

Also check https://github.com/kulshekhar/ts-jest/wiki/Troubleshooting#jestmock-hoisting. I have no time to investigate more right now sorry. In case what I quickly gave you here fixes your bug, thanks for closing this issue.

Thanks @huafu. And sorry for my misleading.

It is not a bug, the test works well as expect. Mocks works fine. Not the case in the trouble shooting.

The only problem is the IDE(as well TS) complain about 'mockImplementation' is not defined in the (actually mocked) function.

Tested putting jest.mock('xxx') call before the actual import ... from 'xxx' in the test file, but doesn't make different.

oh ok, i misunderstood sorry. There is already an issue for this, it's typings for mock or so. It's a won't fix for now. Can't search for the issue now, but there is more info related to that in there, you should look for it.

Found out #576. And it is a good hint to use type case to deal with type issus.
I'll close this one. Thanks a lot for help.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlexGellert picture AlexGellert  路  4Comments

qm3ster picture qm3ster  路  3Comments

jbreckmckye picture jbreckmckye  路  3Comments

golddranks picture golddranks  路  3Comments

ozum picture ozum  路  4Comments