typescript-mockify
Typescript mocking library. Makes it easy to create mocks in typescript. Spies are automatically added on every mock function. Properties that are not mapped in the constructor will get default values.
Installing
$ npm install typescript-mockify --save
Usage
import typescript-mockify
;
If you would have the following class:
You can create a mock like this..
;
The actual instance will be in the instance property
;
Even though typescript-mockify has created spies for every function, you can still declare returnvalues in an easy way
mockedCar .setupMethod"toString".andReturn"my mocked returnvalue" .setupMethod"dummyFunc".andCallFake_.noop;
Or directly fetch the spy of a stubbed function...
.setupMethod"drive".getSpy;
You can also use the callback notation to keep the chain alive
mockedCar
.setupSpy("drive", (driveSpy: Spy) => driveSpy.and.callFake(_.noop))
.setupSpy("toString", (toStringSpy: Spy) => toStringSpy.and.returnValue("I came from the spy"));
Or just use it directly...
;
Example
Just a tiny example to show the difference between the real instance and the mock instance
;console.logcar.speed; // 0car.drive100;console.logcar.speed; // 100car.stop;console.logcar.speed; // 0console.logcar.toString; // brand:vw, speed:0, age:10 .withCallConstructortrue .createInstanceCar, new ConstructorArguments .map"brand", "vw" .map"age", 12 .setupMethod"toString".andReturn"mockedstr"; console.logmockedCar.instance.speed; // 0car.drive100;console.logmockedCar.instance.speed; // 0car.stop;console.logmockedCar.instance.speed; // 0console.logmockedCar.instance.toString; // mocked str