mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

Help Defining Constructor in Mock Object #68

Closed kyle-wrenn closed 6 years ago

kyle-wrenn commented 6 years ago

I'm having an issue mocking an object that's being instantiated using 'new'. I'm trying to Kinesis from AWS which is being constructed as follows:

var kinesis = new AWS.Kinesis({
    apiVersion: kinesisAPIName
});

I'm trying to create a mock object for kinesis:

var mock_aws = {config: {
            update: () => {}
        },
        Kinesis: {
            Kinesis: (params) => {},
            putRecord: (params, callback) => {
                if (params.PartitionKey === 'FAILED_PUT') {
                    callback('FAILED_PUT');
                } else {
                    callback(null, null);
                }
            }
        }
    };

When the Kinesis object is constructed I get a TypeError: AWS.Kinesis is not a constructor

Aghabeiki commented 6 years ago

Its because u define kinesis as properties, not a constructor (Function)

This code will fix ur problem.

class Kinesis {
    constructor(args) {
        console.log("kinesis called with this args:");
        console.dir(args);
    }
}
const mockedAWS = {
    Kinesis: Kinesis
}
mockery.registerMock('aws-sdk', mockedAWS);
var AWS = require('aws-sdk');
var kinesis = new AWS.Kinesis({
    apiVersion: 'kinesisAPIName'
});