2

Got some code in ./fooApi.ts. But I have a mock for it in __mocks__ -- this is a way to make sure that the mock version of your code is imported when using mocks in Jest. This means that when the code runs the actual type of the thing imported will be jest.Mock. But TS doesn't know about the mocks. So I need to cast them with as:

import { createUrl, getToken } from './fooApi';
const mockedCreateUrl = createUrl as jest.Mock;
const mockedGetToken = getToken as jest.Mock;

OK TS is happy with that. But I'm wondering if I can do it in one line. I don't see anything on the type assertions page about this.

Read this answer here and tried:

import { createUrl, getToken } : {createUrl: jest.Mock, getToken: jest.Mock } from './fooApi';

Which resulted in TS1005: 'from' expected. at the first colon.

Any way to turn those 3 lines into one?

jcollum
  • 43,623
  • 55
  • 191
  • 321

1 Answers1

1

Currently, at "compile" time, no way to tell jest that you are importing a mocked module or actual module. Only you know that ./fooApi is already mocked.

You can cast by as operator as your 1st option. But, if you are working with ts-jest, I can suggest a way to cast the fooApi type to mock - use mocked function from ts-jest/untils:

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

describe('fooApi', () => {
  let fooApiMocked: jest.Mocked<typeof fooApi>;

  beforeEach(() => {
    fooApiMocked = mocked(fooApi);

    // fooApiMocked.createUrl, fooApiMocked.getToken are jest.Mock
  });
});
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • well it's a week later and this is the only answer, but I'm gonna wait a bit to mark it as the answer – jcollum Sep 09 '21 at 22:57