TIL Avoiding dependencies in your helper functions
POSTED ON:
TAGS: helpers javascript testing functional-programming
This is a impure function.
import VALID_VALUES_LIST from './constants';
function isValueValid( value ) {
return VALID_VALUES_LIST.includes( value );
}
Why? Because it NEEDS VALID_VALUES_LIST
to work. It depends on it.
One of the super powers of functional programming is pure functions.
function isValueValid( value, validValuesArray = [] ) {
return validValuesArray.includes( value );
}
This is a pure function. You can pass any array in the second param.
Now in your testing library, all of these will work with zero dependencies.
expect( isValueValid( 'hulk', [ 'batman', 'superman' ] ) ).toBe( false );
expect( isValueValid( 'hulk', null ) ).toBe( false );
expect( isValueValid( 'hulk', [] ) ).toBe( false );
expect( isValueValid( 'hulk', [ 'iron man', 'hulk' ] ) ).toBe( true );
Related TILs
Tagged: helpers