Unit Test a Function
Learn how to test a function using different inputs and outputs and how to name the tests.
We'll cover the following...
flat-Map
tests
Let’s try and write the function and tests from the previous lesson using Jasmine.
We want to have the spec file right next to the source file. That way, the spec is separate from the production code but still close at hand.
To that end, we have src/flat-map.js
as the implementation and src/flat-map.spec.js
as the spec.
Run
Run the code playground below.
const SpecReporter = require('jasmine-spec-reporter').SpecReporter jasmine.getEnv().clearReporters(); jasmine.getEnv().addReporter( new SpecReporter({ spec: { displayPending: true, }, }) )
Breakdown
The file src/flat-map.js
contains our code implementing the flatMap
polyfill. In a single line, it invokes the map
function that comes from Array.prototype
.
Then, it takes the result of that, which is an array, and invokes its reduce
function. Note that we refer to a function attached to an object as a method.
The reduce
method takes an accumulator acc
, which passes in along with each member of the array. The result of the callback (acc, n) => acc.concat(n)
is stored in the acc reference and then passed in for the next iteration.
In short, it reduces
an array to a single value.
The Array.prototype.flatMap = function() ...
tells JavaScript: “Attach this flatMap method and make it accessible to every Array instance!”. It allows us to use it like this:
const numbers = [1, 2, 3];
numbers.flatMap()
The file src/flat-map.spec.js
...