How to mock a constructor call in a node.js unit test?

I've written a small node.js module to update twitter using the Twit library

// src/twitterHelper.js

const Twit = require('twit');
const twitterClient = new Twit({
    consumer_key: 'consumer_key',
    consumer_secret: 'consumer_secret',
    access_token: 'access_token',
    access_token_secret: 'access_token_secret'

function updateStatus(params, callback) {'statuses/update', params, function (err, data, response) {
        if (err) {
            console.log(`Error occurred updating status\t${err}`);
        else {
            console.log(`Posted twitter with id ${data.id_str}

exports.updateStatus = updateStatus;

and I've written a unit test for this using mocha, chai, and sinon. But the call to the constructor for Twit is always returning the actual object - how I can replace this with the mock object from the unit test?

// test/twitterHelper.spec.js
const Twit = require('twit')
const expect = require("chai").expect;
const sinon     = require('sinon');
const twitterHelper = require("../src/twitterHelper");

describe("Unit tests for twitter helper", () => {
    const mockTwit = {
        post: (endpoint, params, callback) => {
            console.log(`Called ${endpoint} with ${params}`);

    it("should create a mock twit object", () => { 
        sinon.stub(Twit, 'constructor').returns(mockTwit);
        twitterHelper.updateStatus({status: "New status"});

Read more here:

Content Attribution

This content was originally published by Joseph McCarthy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: