Hi all I m finding jes…

2 minute read

Hi all - I’m finding jest mocks working unexpectedly (or rather not working unexpectedly) in the Nrwl project. I have a lib1 that imports another lib2. In the lib1 test (that existed outside a nrwl project), lib2 is mocked. For some reason, when I use lib2.method1.mockClear, the method mockClear doesn’t exist. Actually - none of the mocking functions exist. The strange thing is - that the debugger sees the mock functions (see attached image).

Responses:

Image 1: the logger mock contains the mocked jest.fn() with the mockClear method in the debugger

Image 2: The error I get when running the test

It seems like a TS issue in the lib itself, because the issue is bypassed if I use TS-ignore for the mocking lines. Can anyone spot it?

can you show how you’re defining the mocked object?

jest has a generic jest.Mocked<T> type that you probably want to use

jest.mock('@insights/logger');

I actually had another issue yesterday which I kind of solved, but since it happened again, I figured there’s something I’m doing wrong in regards to the nx infra

```import { logger } from ‘@insights/logger’;

import { requestLoggerMiddleware } from ‘./request-logger-middleware’;

jest.mock(‘@insights/logger’);

describe(‘request logger’, () => { let mockedReq; let mockedRes;

beforeEach(() => { // @ts-ignore http://logger.info|logger.info.mockClear(); // @ts-ignore logger.error.mockClear(); mockedRes = { statusCode: 200, on: (event, callback) => { callback(); } }; mockedReq = { originalUrl: ‘http://southpark/hellochildren’, method: ‘DELETE’ }; });```

This is the code - logger is just an exported object

(logger.error as jest.Mock).mockClear() would work, i think

AFAIK, typescript can’t infer that the dependency you’re importing is mocked, so it’s typing it as whatever the logger type is

you might be able to do something along the lines of let mockLogger: jest.Mocked<typeof logger>; and set it to logger in a beforeEach

just to have a variable with the convenient type

I tried that yesterday - still didn’t work

I’ll try it in this case - might do :slightly_smiling_face:

Oh - the problem is that I need to mock each and every method on logger now

you shouldn’t have to…jest.Mocked is just a type

I never had this issue before

I’ve been working with jest for quite a while - with TS

(in angular projects - even in nrwl/nx projects)

jest.mock("../api"); import * as api from "../api"; const mockApi = api as jest.Mocked<typeof api>; ^ that’s actually jest’s example of using jest.Mocked

i think older versions of ts-jest had much less strict typechecking

Oh…

explains a lot

Anyway - your dark magic worked :wink:

I’ll have to document it - ppl aren’t gonna like this

It’s adding another line in a test file - which at best is considered a hindrance. Don’t think I want to write down all the things devs think about tests :slightly_smiling_face:

Thanks a lot!

Updated: