Typescript errors when using jest mocks
Use this
import { mocked } from 'ts-jest/utils';
import { foo } from './foo';
jest.mock('./foo');
expect(mocked(foo)).toHaveLength(1);
Following the @nobleare response... a good update will be to wrap your mock implementation into the beforeAll
and clear it into the beforeEach
block:
import { AnalyticsApi } from "../../api/src";
jest.mock("../../api/src");
describe('...', () => {
beforeAll(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
listPolicies: jest.fn().mockResolvedValue('promiseValue')
}));
});
beforeEach(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockClear();
});
});
To override an import, you can do it like so:
import { AnalyticsApi } from "../../api/src";
jest.mock("../../api/src");
let listPolicies = jest.fn(() => {
return Promise.resolve();
});
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
listPolicies,
}));
I fixed this myself. The way that I got it to work was to cast any calls to Server.getAsync
to the specific jest mock type.
let getAsyncMock = Server.getAsync as jest.Mock
or
let getAsyncMock = <jest.Mock>(Server.getAsync)
This gets rid of my errors.