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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With