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
str
parameter is actually a string and notnull
orobject
ornumber
, and so on. - The
callback
parameter is actually afunction
and notnull
orobject
, 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 ...
Access this course and 1400+ top-rated courses and projects.