Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid the need to cast mocked typescript imports

I'm importing a mocked function, but since Typescript doesn't seem to know that Jest changes the import to a mock, I have to cast the imported function before I can use mock methods like mockReturnValue etc.

jest.mock('../myImport');
import { thisFunctionIsMocked } from '../myImport'

/* ... */

(<Mock<any>>thisFunctionIsMocked).mockReturnValue(42);

If I don't cast the import, Typescript claims that the mock function methods don't exist. Is there a better way to do this?

like image 687
Brian Avatar asked Feb 06 '17 17:02

Brian


1 Answers

I've been looking for the same. Unfortunately, doesn't seem to be much out there on how to handle this. Some alternatives, however.

1) Slightly different syntax for what you're already doing:

(thisFunctionIsMocked as jest.Mock).mockReturnValue(42);

2) Use require and cast there instead:

const thisFunctionIsMocked = require('../myImport') as jest.Mock;

Update:

ts-jest now has a mocked helper which you can use. You still need to use it when you reference mocked imports, but it means that the type signature of the original source isn't lost:

import { mocked } from 'ts-jest/utils';

test('direct', () => {
  foo.name();
  expect(mocked(foo.name).mock.calls).toHaveLength(1);
});
like image 149
lobati Avatar answered Oct 01 '22 05:10

lobati