Functional Programming Unit Testing in Node (Part 6)

DZone 's Guide to

Functional Programming Unit Testing in Node (Part 6)

In Part 6 of this six-part series, we wrap up by discussing unit testing the noop next method, wrapping noop in pure functions, and code coverage.

· Web Dev Zone ·
Free Resource

Welcome to Part 6, the final installment in this series. Below we cover unit testing the noop next, how to create pure functions that wrap noop so you can compose them, and finally using code coverage to strategically hit the last code that's not covered.


This is a 6 part series on refactoring imperative code in Node to a functional programming style with unit tests. You are currently on Part 6.

The last part is deal with next. THIS is where I'd say it's ok to use mocks since it's a noop, but you do want to ensure it was called at least once, without an Error in the happy path, and with an Error in the bad path.

... but you've made it this far which means you are FAR from ok, you're amazing. NO MOCKS!

Here are the basics of testing noops. You sometimes KNOW if they did something, or how they can affect things based on their arguments. In next's case, he'll signal everything is ok if passed no arguments, and something went wrong and to stop the current connect middleware chain if an Error is passed, much like a Promise chain. We also know that next always returns undefined.

Ors (Yes, Tales of Legendia Was Bad)

One simple way is to just inject it into the existing Promise chain we have:

.then( info => next() || Promise.resolve(info))
.catch( error => next(error) || Promise.reject(error)))

This'll make the connect middleware happy as well as satisfying our unit tests expecting either an email info out, or a rejected promise with error.

Pass Through

Much like you log Promise or other Monad chains, simply make a pass through function.

const nextAndResolve = curry((next, info) => next() || Promise.resolve(info))
const nextAndError = curry((next, error) => next(error) || Promise.reject(error))

And since we already know what the next is, we can just attach 'em to the end of the Promise chain, similar to above:


"Wat!?" you may be saying, "all you did was wrap that previous example in functions." Yup, they're pure, and you can test those in isolation vs. test that gigantic Promise chain with 20 billion stubs.

describe('nextAndResolve when called', () => {
    it('should fulfill', () => {
        return expect(nextAndResolve(noop, 'info')).to.be.fulfilled
    it('should resolve', () => {
        return expect(nextAndResolve(noop, 'info')).to.become('info')

Let's do the same for error:

describe('nextAndError when called', () => {
    it('should fulfill', () => {
        return expect(nextAndError(noop, new Error('they know what is what'))).to.be.rejected
    }) it('should resolve', () => {
        const datBoom = new Error('they just strut') return expect(nextAndError(noop, datBoom)).to.rejectedWith(datBoom)

If you're Spidey Sense left over from your Imperative/OOP days is tingling, and you really want to create a mock or spy, go for it.

I would rather you focus your time on creating pure Promise chains vs. investing in better testing side effects using the connect middleware.

Only two functions to go, and we're up in the hundreds.

sendEmail ... or Not

The sendEmailOrNext is a textbook case of copy-pasta coding. We'll duplicate our previous sendEmail unit tests since they have some yum yum stubs:

describe('sendEmailOrNext when called', () => { ...
    const reqStubNoFiles = {
        cookie: {
            sessionID: '1'
    }...it('should work with good stubs', () => {
        return expect(sendEmailOrNext(readFileStub, configStub, createTransportStub, getUserEmailStub, renderStub, reqStub, resStub, nextStub)).to.be.fulfilled
    }) it('should fail with bad stubs', () => {
        return expect(sendEmailOrNext(readFileStubBad, configStub, createTransportStub, getUserEmailStub, renderStub, reqStub, resStub, nextStub)).to.be.rejected
    }) it('should resolve with false if no files', () => {
        return expect(sendEmailOrNext(readFileStub, configStub, createTransportStub, getUserEmailStub, renderStub, reqStubNoFiles, resStub, nextStub)).to.become(false)

I've left out all the stubs, save the new one that shows, if we have no files, it just bypasses the entire thing, calls next with no value signaling to connect we're good to go and finished, but still returning a useful value of false to say we didn't do what we're supposed to since we couldn't find any files.

There and Back Again

Oh look, coverage found yet another noop, imagine that.

const logPort = port => console.log(`Example app listening on port ${port}!`) || true 

And the 1 test:

describe('logPort when called', () => {
    it('should be true with a port of 222', () => {

If you really want to create a mock/spy for console.log, I admire your tenacity, Haskell awaits you with open arms in your future. Remember me when you're at the top and you've bested Mr. Popo on the Lookout.

... however, if you're not using console.log, and instead using a known Node logger like Pino, well, heh, you SHOULD!

I should point out some well known Clojure guys think I'm going overboard:

If you read the Twitter thread, an Elm guy schools me, and the Haskell cats show me how even there you can trick Haskell, but still acknowledge (kind of?) the purity pain.

Running coverage, we get:

Welcome to hundreds country. Congratulations on making this far, and not one import of sinon to be found. Don't worry, deadlines and noops are all over the place in the JavaScript world, and sinon's mock creation ability is not something to be shunned, but embraced as a helpful addition to your toolset. Like all technical debt, create it intentionally with notes about why, what to remove, context around creating it, etc. in code comments around it.

Hopefully you've seen how creating small, pure functions, makes unit testing with small stubs a lot easier, faster, and leads to more predictable code. You've seen how you can use Functional Programming best practices, yet still co-exist with noops in imperative code, and classes and scope in OOP.

I should also point out that writing imperative or OOP code like this is a great way to learn how to write FP. Sometimes our brains are wired to flesh out ideas in those styles, and that's great. Whatever works to get the ideas down. On the front-end, using vanilla React's classes vs. recompose ... or even just components functions only. Functional Programming will still hurt just as much as Imperative or OOP if you've got a not-so-figured out idea on how some problems should be solved and structured. Write it so it feels comfortable, then refactor and test to purity.

You've seen how to compose these functions together synchronously via operands like && and ||, using flow/ compose. You've also seen how to compose them in Promise chains and Promise.all, curried or not.

You've also seen how 100% unit test coverage in a FP code base still has bugs that are only surfaced with concrete implementations using integration testing, such as with Mountebank.

Node is often used for APIs that have little to no state and are just orchestration layers for a variety of XML SOAP, JSON, and text. The no mutable state of Functional Programming works nicely with that concept in ensuring those no state to debug.

Conversely, if you're dealing with a lot of state such as database connections and streaming text files, not only can you see how you can test such challenging areas using pure functions, but also how many of those things can be run at the same time to speed things up with stepping on each other through global variables.

Props to Cliff Meyers for teaching me what Mountebank is.

The code is on GitHub

code coverage, node.js, tutorial, unit testing, web dev

Published at DZone with permission of Jesse Warden , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}