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 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.
const SpecReporter = require('jasmine-spec-reporter').SpecReporter jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter( new SpecReporter({ // add jasmine-spec-reporter spec: { displayPending: true, }, }) )
The file src/maybe-string.spec.js
contains the test cases for the maybeString
function. Since that function accepts a callback and has logic that decides when to call that, the tests need to ensure that the callback is called when it’s supposed to and not otherwise.
The spy
The ...