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

183
Vistas
toBeCalled returns false even though the mock function is being called

I'm testing a koa server. The `verifyRequest' is a middleware which calls http request internally, so I want to mock the function and test that the function is called properly.

The first time I run the mock function, toBeCalled returns true as expected. However, after executing mockClear, toBeCalled returns false, even though the mock function is executed (please see the logs below).

Can anyone explain the curious behavior? And please let me know how I can run mock clear correctly.

// server.test.ts

import {verifyRequest} from '../middlewares/verifyRequest';
import {mocked} from 'jest-mock';
import {agent} from './lib/agent';

jest.mock('../middlewares/verifyRequest', () => {
  return {
    verifyRequest: jest.fn().mockImplementation(
      (): Middleware<DefaultState, Context, any> => {
        return async function (_ctx, next) {
          console.log('mocked verifyRequest is called!');
          await next();
        };
      }
    ),
  };
});

afterEach(() => {
  mocked(verifyRequest).mockClear();
});

it('test-one', async () => {
  await agent.get('/'); // verifyRequest will be called as a middleware
  console.log('test-one', mocked(verifyRequest).mock);
  expect(verifyRequest).toBeCalled();
});
it('test-two', async () => {
  await agent.get('/');
  console.log('test-two', mocked(verifyRequest).mock);
  expect(verifyRequest).toBeCalled();
});
// ../middlewares/verifyRequest
import compose from 'koa-compose';
import {Context, DefaultState, Middleware} from 'koa';

export function verifyRequest(): Middleware<DefaultState, Context, any> {
  return compose([
    ...myMiddlwares
  ]);
}

    console.log
      mocked verifyRequest is called!

    console.log
      test-one {
        calls: [ [ [Object] ], [ [Object] ], [ [Object] ], [ [Object] ] ],
        instances: [ undefined, undefined, undefined, undefined ],
        invocationCallOrder: [ 5, 6, 9, 10 ],
        results: [
          { type: 'return', value: [AsyncFunction (anonymous)] },
          { type: 'return', value: [AsyncFunction (anonymous)] },
          { type: 'return', value: [AsyncFunction (anonymous)] },
          { type: 'return', value: [AsyncFunction (anonymous)] }
        ]
      }

    console.log
      mocked verifyRequest is called!

    console.log
      test-two { calls: [], instances: [], invocationCallOrder: [], results: [] }
versions
"jest": "^27.4.7",
"jest-mock": "^27.4.6",
"ts-jest": "^27.1.3",
about 4 years ago · Juan Pablo Isaza
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