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:

     .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


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


/* global describe it */


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')
    .then((items) => {
    .then(done, done)
  it('should throw an error', function (done) {
    .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.