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

222
Visualizações
How to mock "new Date()" which is inside functional component?
  1. I have the functional component "order". It has a lot of unimportant code (in this context I mean) and there are a few "new Date()" calls.
  2. When the test snapshot of this component is creating, "new Date()" returns the current date object. Hence if I run test for this component at least one moment later, snapshots will differ from each other.
  3. Thus I have tried to mock "new Date()" somehow like this:
    import renderer from 'react-test-renderer';

    test('TestName', async () => {
        let componentRenderer = null;

        const now = new Date('2000-01-01T10:00:00.135Z');
        jest.spyOn(global, 'Date').mockImplementation(() => now);
        await renderer.act(async () => {
          componentRenderer = await renderer.create(<Order orderId={0} />);
        });

        const orderFormComponent = componentRenderer.toJSON();
        expect(orderFormComponent).toMatchSnapshot();
      });
  1. It doesn't work at all. It is always a regular "new Date()" call. I mean it works just fine if you call it right in the testing code below the mock lines. But I need mocked "new Date()" to be called inside my functional component when it is being created here:

    renderer.create(<Order orderId={0} />)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I've found this approach to be the most generic one:

  1. Create a MockDate:
export class MockDate extends Date {
    constructor(arg) {
        super(arg || 1);
    }
}
  1. Use the created mock in jest:
beforeAll(() => {
    global.Date = MockDate as DateConstructor;
});

afterAll(() => {
    global.Date = Date;
});

Then, in your tests, console.log(new Date()) === MockDate 1970-01-01T00:00:00.001Z

about 4 years ago · Juan Pablo Isaza Relatório
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