Search⌘ K
AI Features

Test a Function Depending on Other Functions

Explore how to test JavaScript functions relying on other functions by using Jasmine's spy and spyOn features. Understand creating mock functions, verifying callback calls, handling different parameters, and testing asynchronous behavior for robust unit tests.

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. ...