Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
How to jest.mock "git-simple" branchLocal function?

I use the simple-git package. I have the following function:

import simpleGit from 'simple-git';

/**
 * The function returns the ticket Id, is presents, in the branch name
 * @returns ticket Id
 */
export const getTicketIdFromBranchName = async (ticketRegex: RegExp) => {
    const git = simpleGit();

    try {
        const localBranches = await git.branchLocal();
        const currentBranch = localBranches.current;
        const currentBranchTicketMatches = currentBranch.match(ticketRegex);

        if (currentBranchTicketMatches) {
            return currentBranchTicketMatches[0];
        }

        return null;
    } catch {
        return null;
    }
};

I try to create a unit-test for this function:

import { getTicketIdFromBranchName } from '@/utils/git-info';

const TICKET_ID_REGEX = /((?<!([A-Z]{1,10})-?)[A-Z]+-\d+)/.source;

describe('[utils/git-info]', () => {
    it('getTicketIdFromBranchName | Function should proper ticket Id when there is one', async () => {
        const ticketId = 'CLO-1234';

        jest.mock('simple-git', () => {
            const mGit = {
                branchLocal: jest.fn(() => Promise.resolve({ current: `${ticketId} DUMMY TEST` })),
            };

            return jest.fn(() => mGit);
        });

        const result = await getTicketIdFromBranchName(new RegExp(TICKET_ID_REGEX));

        expect(result === ticketId).toEqual(true);
    });
});

But the unit-test fails. I says I expected to get true but it got false in the final line.

I guess I use jest.mock in the wrong way.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The official documentation has a key description of the use of jest.mock.

Note: In order to mock properly, Jest needs jest.mock('moduleName') to be in the same scope as the require/import statement.

You call the jest.mock('moduleName') inside test case function scope, but import the git-info module in module scope. That's why mock doesn't work.

Use require('moduleName') or await import('moduleName') in test case function. The order of the require/import and jest.mock() statements does not matter.

git-info.js:

import simpleGit from 'simple-git';

/**
 * The function returns the ticket Id, is presents, in the branch name
 * @returns ticket Id
 */
export const getTicketIdFromBranchName = async (ticketRegex) => {
  const git = simpleGit();

  try {
    const localBranches = await git.branchLocal();
    const currentBranch = localBranches.current;
    const currentBranchTicketMatches = currentBranch.match(ticketRegex);

    if (currentBranchTicketMatches) {
      return currentBranchTicketMatches[0];
    }

    return null;
  } catch {
    return null;
  }
};

git-info.test.js:

const TICKET_ID_REGEX = /((?<!([A-Z]{1,10})-?)[A-Z]+-\d+)/.source;

describe('[utils/git-info]', () => {
  it('getTicketIdFromBranchName | Function should proper ticket Id when there is one', async () => {
    const { getTicketIdFromBranchName } = await import('./git-info');
    const ticketId = 'CLO-1234';

    jest.mock(
      'simple-git',
      () => {
        const mGit = {
          branchLocal: jest.fn(() => Promise.resolve({ current: `${ticketId} DUMMY TEST` })),
        };

        return jest.fn(() => mGit);
      },
      { virtual: true }
    );

    const result = await getTicketIdFromBranchName(new RegExp(TICKET_ID_REGEX));

    expect(result === ticketId).toEqual(true);
  });
});

Test result:

 PASS  stackoverflow/71808909/git-info.test.js (7.439 s)
  [utils/git-info]
    ✓ getTicketIdFromBranchName | Function should proper ticket Id when there is one (6892 ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |   84.62 |       50 |     100 |   81.82 |                   
 git-info.js |   84.62 |       50 |     100 |   81.82 | 19-21             
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.215 s, estimated 9 s

package version: "jest": "^26.6.3"

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda