Test a Function Depending on Other Functions
Learn to test functions that take other functions as parameters and depend on them..
The maybeString function
The function maybeString takes a parameter and a callback. It calls the callback only if the parameter is a string. The callback is the function that maybeString depends on for its logic.
function maybeString(str, callback) {
if (typeof str === 'string' && typeof callback === 'function') {
return callback(str);
}
}
The expression typeof str === 'string' && typeof callback === 'function' is true only if:
- The
strparameter is actually a string and notnullorobjectornumber, and so on. - The
callbackparameter is actually afunctionand notnullorobject, and so on.
If the above is true, the function returns the result of calling callback and passing str.
If the above is not true, our function returns undefined. This is because JavaScript considers any function that completes without hitting a return statement to have a return undefined; or return; MDN Function.
Mocking and spying
To be able to test maybeString, we need to provide the ...