mockbuilder

0.1.1 • Public • Published

mockbuilder

Easily mock objects and instances of objects in Javascript using the Java builder concept

Installation

npm install mockbuilder --save

Usage

const builder = require('mockbuilder');
 
const johnBuilder = builder()
  .set('firstname', 'John')
  .set('lastname', 'Smith');
  
const jamesBuilder = johnBuilder
  .set('firstname', 'James');
  
const james = jamesBuilder.build(); // { firstname: 'James', lastname: 'Smith' } 
const john = johnBuilder.build(); // { firstname: 'John', lastname: 'Smith }

It can also be used with constructors:

function Person(fname, lname) {
  this.fname = fname;
  this.lname = lname;
}
 
const personBuilder = builder()
  .construct(Person)
  .set('species', 'homo sapien')
  .set('getFullName', function () { return this.fname + ' ' + this.lname; })
  .set('getSpecies', function () { return this.species; };
  
const john = personBuilder.build('John', 'Smith');
const james = personBuilder.build('James', 'Smith');
 
john.getFullName(); // John Smith
james.getFullName(); // James Smith
 
john.getSpecies(); // homo sapien
james.getSpecies(); // homo sapien

And since this package is for the purposes of testing mocked objects you can set spies for your functions:

const sinon = require('sinon');
 
const peter = personBuilder
  .set('getFullName', function () { return sinon.spy(); }, true)
  .build('Peter', 'J');
  
peter.getFullName();
peter.getFullName.called; // true

Note Notice that a third parameter was passed to the set method. It expects a boolean (defaults to false). If set to true, when build is called it will set the value for that key as the return value of the function that is passed in. This allows the set up of spies since each call to build will return a new instance of sinon.spy in this case.

If an array is passed in to set with the third parameter set to true, the builder will iterate through the array and set the value of a given index with the return value of the function at that index.

Testing

To test, just run:

npm test

Readme

Keywords

none

Package Sidebar

Install

npm i mockbuilder

Weekly Downloads

0

Version

0.1.1

License

Apache-2.0

Last publish

Collaborators

  • petejodo