最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock nanoid for testing? - Stack Overflow

programmeradmin2浏览0评论

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: "[email protected]" };
    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!

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: "[email protected]" };
    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!

Share Improve this question asked Jun 9, 2021 at 5:44 ffx292ffx292 7093 gold badges20 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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: '[email protected]' };
    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: '[email protected]', 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
发布评论

评论列表(0)

  1. 暂无评论