Skip to content
Advertisement

How to mock nanoid for testing?

I’m trying to mock nanoid for my testing but it doesn’t seem to be working.

my function

JavaScript

My test:

JavaScript

So basically I’m struggling to figure out how to mock the nanoid which is generated inside the function.

I’ve tried the following at the top of the file:

JavaScript

however it doesn’t work at all.

Any help would be appreciated!

Advertisement

Answer

You didn’t mock the nanoid module correctly. It uses named exports to export the nanoid function.

Use jest.mock(moduleName, factory, options) is correct, the factory argument is optional. It will create a mocked nanoid function.

Besides, you can use the mocked function from ts-jest/utils to handle the TS type.

E.g.

Example.ts:

JavaScript

Example.test.ts:

JavaScript

test result:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement