ineeda
Auto-mocking with Proxies! Works best with TypeScript, but works just as well with JavaScript!
Installation:
npm install ineeda --save-dev
Mocking:
To get a mock of a concrete class:
; ; ;console.loghero.age; // [IneedaProxy] (truthy!)console.loghero.weapon.isMagic; // [IneedaProxy] (truthy!)console.loghero.weapon.sharpen; // Error('"sharpen" is not implemented.'); ;console.logbonnie.name; // 'Bonnie'
To get a mock of an interface:
; ; ;horse.hero.weapon.sharpen; // Error('"sharpen" is not implemented.');
To get a mock of a concrete class that is an actual instance of that class:
; ; ;console.logrealHero instanceof Hero; // true;
To get a factory that produces mocks of a concrete class:
; ; ;;
Intercepting:
Overriding proxied values:
Since the result of a call to ineeda
is a proxy, it will happily pretend to be any kind of object you ask it to be! That can cause some issues, such as when dealing with Promises
or Observables
. To get around that, you can use intercept
.
When you need a fake Promise
or Observable
:
; looksLikePromisemockObject; // true;looksLikePromisemockObject.intercept; // false; ;;
Remembering which properties need to be intercepted can be a pain, and rather error prone. Alternatively, you can assign a key
, which you can use to set up specific values that should be intercepted. In your test config you might do something like the following:
// Prevent Bluebird from thinking ineeda mocks are Promises:ineeda.interceptPromise, ; // Prevent RxJS from thinking ineeda mocks are Schedulers:ineeda.interceptObservable, ;
Then later, in your tests, you could do the following:
; looksLikePromisemockObject; // true;looksLikePromisemockObject.interceptPromise; // false; ;;
You can also globally intercept something on all objects, by using the intercept
method without the key
:
ineeda.intercept({ // Prevent zone.js from thinking ineeda mocks are unconfigurable: __zone_symbol__unconfigurables: null});
Adding behaviour to proxied values:
intercept
can also be used to augment the behaviour of all mocks. One example might be to make every mocked function a spy
.
// Prevent sinon from thinking ineeda mocks are already spies:ineeda.intercept; // Intercept all values that are functions and turn it into a stub:ineeda.intercept; ;mockObject.someMethod1, 2, 3; // Using sinon-chai:expectmockObject.someMethod.to.have.been.calledWith1, 2, 3;