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