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

305
Visualizações
How to test a function for side-effects using Jest and JavaScript

I'm using Jest for testing.
I want to test if myFunction( myArray ) has no side-effects:

test("that there are no side-effects" ...)

How do I write a test that myArray doesn't get changed by myFunction?

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

0

In strict mode, you can freeze the array before testing the function, and any direction mutation will throw an exception:

Note that the elements of the array in the code below are primitives, but that preventing mutations of nested objects (including arrays), will require that those objects are also frozen.

<script type="module">

function test (name, fn) {
  try {
    fn();
    console.log('✅', name);
  }
  catch (ex) {
    console.log('❌', name);
    console.log(String(ex));
  }
}

function doubleArrayValues (array) {
  for (let i = 0; i < array.length; i += 1) {
    array[i] *= 2;
  }
}

function myFunctionPure (array) {
  const copy = [...array];
  doubleArrayValues(copy);
  return copy;
}

function myFunctionImpure (array) {
  doubleArrayValues(array);
  return array;
}

test('myFunctionPure: has no side-effects', () => {
  const myArray = Object.freeze([1, 2, 3]);
  myFunctionPure(myArray);
});

test('myFunctionImpure: has no side-effects', () => {
  const myArray = Object.freeze([1, 2, 3]);
  myFunctionImpure(myArray);
});

</script>

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