0

Is there a less verbose way of typing a mocked module than having to use as ?

import { fetchUsers } from './services/usesService';
jest.mock('./services/userService');

describe('something', () => {
  beforeEach(() => {
    (fetchBrief as jest.Mock).mockClear(); // this works
    fetchUsers.mockClear(); // Property 'mockClear' does not exist on type...
  });
});
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
alextrastero
  • 3,703
  • 2
  • 21
  • 31
  • Thanks! but not really since it's still verbose, but I'll use `as` if I have too – alextrastero Oct 28 '20 at 15:27
  • There are numerous answers with various approaches, but the point is more to drive any additional answers to that same place so they're all together. In cases like this it's better to get attention with a bounty, otherwise the answers end up scattered all around the site. – jonrsharpe Oct 28 '20 at 15:29

1 Answers1

0

I've been having success overwriting the module's methods with mocks manually and ts plays super nice with them:

import * as userService from './services/usesService';

const fetchUsersMock = jest.mock();
const fetchBriefMock = jest.mock();

userService.fetchUsers = fetchUsersMock;
userService.fetchBrief = fetchBriefMock;

describe('something', () => {
  beforeEach(() => {
    fetchBriefMock.mockClear();
    fetchUsers.mockClear();
  });
});
Eric Tucker
  • 6,144
  • 1
  • 22
  • 36