Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!