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

  public async createApp(appDto: ApplicationDto): Promise<string> {
    const appWithToken = { ...appDto, accessToken: nanoid() };
    const application = await this.applicationModel.create(appWithToken);

    return application.id;
  }

My test:

  beforeEach(() => {
    mockRepository.create.mockResolvedValueOnce({ id: mockId });
  });

  test("creates application and returns an id", async () => {
    const mockAppDto: ApplicationDto = { email: "123@mock.com" };
    const application = await applicationService.createApplication(mockAppDto);

    expect(mockRepository.create).toHaveBeenCalledWith(mockAppDto); //how do I mock the nanoid here?
    expect(application).toBe(mockId);
  });

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:

jest.mock('nanoid', () => 'mock id');

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:

import { nanoid } from 'nanoid';

export interface ApplicationDto {}

export class Example {
  constructor(private applicationModel) {}

  public async createApp(appDto: ApplicationDto): Promise<string> {
    const appWithToken = { ...appDto, accessToken: nanoid() };
    const application = await this.applicationModel.create(appWithToken);

    return application.id;
  }
}

Example.test.ts:

import { nanoid } from 'nanoid';
import { Example, ApplicationDto } from './Example';
import { mocked } from 'ts-jest/utils';

jest.mock('nanoid');

const mnanoid = mocked(nanoid);

describe('67898249', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    mnanoid.mockReturnValueOnce('mock id');
    const mockAppDto: ApplicationDto = { email: '123@mock.com' };
    const mockApplicationModel = { create: jest.fn().mockReturnValueOnce({ id: 1 }) };
    const example = new Example(mockApplicationModel);
    const actual = await example.createApp(mockAppDto);
    expect(actual).toEqual(1);
    expect(mockApplicationModel.create).toBeCalledWith({ email: '123@mock.com', accessToken: 'mock id' });
  });
});

test result:

 PASS  examples/67898249/Example.test.ts (9.134 s)
  67898249
    ✓ should pass (4 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 Example.ts |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.1 s
Advertisement