I'm using the Jest testing library to test a function that invokes a callback that takes two parameters, element[i]
, and i
.
Here is the function I am to test:
const each = (elements, cb) => {
for (let i = 0; i < elements.length; i++) {
cb(elements[i], i);
}
};
I know the array will only have numbers, so in the testing function I'm trying to make the callback simply add the index to each number in the array; e.g., it should change an array of [1, 2, 3, 4]
to [1, 3, 5, 7]
.
Here is what I tried to do:
const arrayFunctions = require('./arrays');
describe('Arrays', () => {
it('each', () => {
const callBack = (elem, indx) => {
elem += indx;
}
const arr = [1, 2, 3, 4];
arrayFunctions.each(arr, callBack);
expect(arr).toEqual([1, 3, 5, 7]);
})
});
And here is the error I'm getting:
Received:
[1, 2, 3, 4]
Difference:
- Expected
+ Received
Array [
1,
+ 2,
3,
- 5,
- 7,
+ 4,
]
15 | const arr = [1, 2, 3, 4];
16 | arrayFunctions.each(arr, callBack);
> 17 | expect(arr).toEqual([1, 3, 5, 7]);
| ^
18 | })
19 | });
20 |
at Object.it (advanced-javascript/arrays.spec.js:17:21)
Why is it not modifying the array as expected? To reiterate with an even simpler example, why does this work:
const arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
arr[i] += i;
}
console.log(arr) // [1, 3, 5, 7];
While this doesn't?
const arr = [1, 2, 3, 4];
each(arr, callBack);
console.log(arr); // [1, 2, 3, 4];