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

296
Vistas
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 Respuestas
Responde la pregunta

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 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