0

I am earning unit testing. I know that best practice is that the functions should have local scope and they return something for example

export function test(arr) {
    let arr2 = [];
    for(let i = 0;i < arr.length;i++) {
        if(arr[i] % 2 === 0) {
            arr2.push(arr[i])
        }
    }
    return arr2;
}

i can write the test for this function very simple - where i will expect some result

import { it, expect } from 'vitest';

it('should return even numbers', () => {
    let result = test([1,2,3,4]);
    expect(result).toEqual([2,4])
})

but I wonder, in functions where the global scope is modified from some function and the function is not returning anything for example

let arr2 = [];
export function test(arr) {
    for(let i = 0;i < arr.length;i++) {
        if(arr[i] % 2 === 0) {
            arr2.push(arr[i])
        }
    }
}

how can i write test for such a functions ? How can i assume that arr2 will containt [2,4] at the end ?

JohnJS
  • 35
  • 3
  • This is why you avoid global state to start with - it's hard to test, hard to reason about. Maybe you factor out e.g. `function addTo(destination, source) { ... }`, which can easily be tested, then `test` just does `addTo(arr2, arr)`. But without the context of why you're modifying `arr2` to start with it's hard to say what the "right" answer might be. – jonrsharpe Aug 02 '22 at 09:19
  • @jonrsharpe right john, but let's say that I recived a project where a lot of functions are modyfing global scope and i need to test them instead to refactor all of them – JohnJS Aug 02 '22 at 09:22
  • Then I'd question the point of unit testing at all. Test at a higher level, don't couple to implementation details especially of poorly factored code. – jonrsharpe Aug 02 '22 at 10:04

0 Answers0