Using nock with a socket connection

I’m working on a Node.JS app that connects to a unix socket, or named pipe, as it’s called on Windows.

 

As part of my tests, I wanted to mock the connection and nock seemed the likely choice. One problem, there was nothing in the docs about socket connections, and the internet didn’t seem to have ever tried this either. So I decided to do a quick writeup for myself and others in the feature.

Thanks to nock’s recording feature it turns out that nock treats sockets connections as localhost. Here is the code:

nock('http://localhost:80')
    .get('/info')
     .reply(200, {
         Containers: 0
})

Much easier than I thought it would be, and you get to guess what I’m making. Happy hacking!

 

Using Mocha with Q and Promises

There are many posts that explain how to use promise libraries to wrap existing JavaScript functions that use callbacks, but very few that explain how to write a function that returns a promise from scratch.

We will be using Q, a promise library that conforms to the Promises/A++ spec.

The magic here is going to be Q’s Deferred method.

Since my use case was to use this with Mocha, a very popular testing library for NodeJS and Javascript, the  code examples for creating and using the function will be in the form of a unit test

Example Code

file.js

const Q = require('q')
 
function myCoolFunction(currentTimestamp) {
  var deferred = Q.defer()
  if (currentTimestamp) {
    deferred.resolve(['1'])
  } else {
    deferred.reject(new Error('Missing timestamp'))
  }
  return deferred.promise
}
 
module.exports = {
  getCurrentItems,
}

index.spec.js

/* global describe it */

require('chai').should()

require('q')
 
const index = require('./index.js')
 
describe('Schedule', function () {
  it('should return one entry for today', function (done) {
    const rightNow = new Date('2017-04-02 03:30:00 EST')
    index.myCoolFunction(rightNow)
    .then((items) => {
      items.length.should.equal(1)
    })
    .then(done, done)
  })
  it('should throw an error', function (done) {
    index.myCoolFunction()
    .catch((err) => {
      err.message.should.equal('Missing timestamp')
    })
    .then(done, done)
  })
})

I hope this code saves you some time when learning how to write pre-ES6 promised functions.