Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda