Test a Function Depending on Other Functions

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 not null or object or number, and so on.
  • The callback parameter is actually a function and not null or object, 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 callback function. Instead of providing just any function, we’ll use a construct called spy. This is a function that monitors its calls and can give a specified response, or a mock function. Such a function takes the place of callback, and we can:

  • Tell it what to return.

  • Tell it to throw an error.

  • Ask it how many times it was called and what parameters it was called with.

Run the code playground below for an example of testing a function using mocks.

Get hands-on with 1200+ tech skills courses.