Readable error messages (ex. 'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).')
Installation
npm install @typestrong/ts-mockito --save-dev
Usage
Basics
// Creating mocklet mockedFoo:Foo = mock(Foo);// Getting instance from mocklet foo:Foo = instance(mockedFoo);// Using instance in source codefoo.getBar(3);foo.getBar(5);// Explicit, readable verificationverify(mockedFoo.getBar(3)).called();verify(mockedFoo.getBar(anything())).called();
Stubbing method calls
// Creating mocklet mockedFoo:Foo = mock(Foo);// stub method before executionwhen(mockedFoo.getBar(3)).thenReturn('three');// Getting instancelet foo:Foo = instance(mockedFoo);// prints threeconsole.log(foo.getBar(3));// prints null, because "getBar(999)" was not stubbedconsole.log(foo.getBar(999));
Stubbing getter value
// Creating mocklet mockedFoo:Foo = mock(Foo);// stub getter before executionwhen(mockedFoo.sampleGetter).thenReturn('three');// Getting instancelet foo:Foo = instance(mockedFoo);// prints threeconsole.log(foo.sampleGetter);
Stubbing property values that have no getters
Syntax is the same as with getter values.
Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).
Call count verification
// Creating mocklet mockedFoo:Foo = mock(Foo);// Getting instancelet foo:Foo = instance(mockedFoo);// Some callsfoo.getBar(1);foo.getBar(2);foo.getBar(2);foo.getBar(3);// Call count verificationverify(mockedFoo.getBar(1)).once(); // was called with arg === 1 only onceverify(mockedFoo.getBar(2)).twice(); // was called with arg === 2 exactly two timesverify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three timesverify(mockedFoo.getBar(anyNumber()).times(4); // was called with any number arg exactly four timesverify(mockedFoo.getBar(2)).atLeast(2); // was called with arg === 2 min two timesverify(mockedFoo.getBar(anything())).atMost(4); // was called with any argument max four timesverify(mockedFoo.getBar(4)).never(); // was never called with arg === 4
Call order verification
// Creating mocklet mockedFoo:Foo = mock(Foo);let mockedBar:Bar = mock(Bar);// Getting instancelet foo:Foo = instance(mockedFoo);let bar:Bar = instance(mockedBar);// Some callsfoo.getBar(1);bar.getFoo(2);// Call order verificationverify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2)); // foo.getBar(1) has been called before bar.getFoo(2)verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1)); // bar.getFoo(2) has been called before foo.getBar(1)verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999)); // throws error (mockedBar.getFoo(999999) has never been called)
You can also stub method with your own implementation
let mockedFoo:Foo = mock(Foo);let foo:Foo = instance(mockedFoo);when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => { return arg1 * arg2; });// prints '50' because we've changed sum method implementation to multiply!console.log(foo.sumTwoNumbers(5, 10));
Resolving / rejecting promises
You can also stub method to resolve / reject promise
let mockedFoo:Foo = mock(Foo);when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));
Resetting mock calls
You can reset just mock call counter
// Creating mocklet mockedFoo:Foo = mock(Foo);// Getting instancelet foo:Foo = instance(mockedFoo);// Some callsfoo.getBar(1);foo.getBar(1);verify(mockedFoo.getBar(1)).twice(); // getBar with arg "1" has been called twice// Reset mockresetCalls(mockedFoo);// Call count verificationverify(mockedFoo.getBar(1)).never(); // has never been called after reset
You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)
Resetting mock
Or reset mock call counter with all stubs
// Creating mocklet mockedFoo:Foo = mock(Foo);when(mockedFoo.getBar(1)).thenReturn("one").// Getting instancelet foo:Foo = instance(mockedFoo);// Some callsconsole.log(foo.getBar(1)); // "one" - as defined in stubconsole.log(foo.getBar(1)); // "one" - as defined in stubverify(mockedFoo.getBar(1)).twice(); // getBar with arg "1" has been called twice// Reset mockreset(mockedFoo);// Call count verificationverify(mockedFoo.getBar(1)).never(); // has never been called after resetconsole.log(foo.getBar(1)); // null - previously added stub has been removed
You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)
Capturing method arguments
let mockedFoo:Foo = mock(Foo);let foo:Foo = instance(mockedFoo);// Call methodfoo.sumTwoNumbers(1, 2);// Check first arg captor valuesconst [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();console.log(firstArg); // prints 1console.log(secondArg); // prints 2
You can also get other calls using first(), second(), byCallIndex(3) and more...
Recording multiple behaviors
You can set multiple returning values for same matching values
const mockedFoo:Foo = mock(Foo);when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');const foo:Foo = instance(mockedFoo);console.log(foo.getBar(1)); // oneconsole.log(foo.getBar(1)); // twoconsole.log(foo.getBar(1)); // threeconsole.log(foo.getBar(1)); // three - last defined behavior will be repeated infinitely
Another example with specific values
let mockedFoo:Foo = mock(Foo);when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');when(mockedFoo.getBar(2)).thenReturn('two');let foo:Foo = instance(mockedFoo);console.log(foo.getBar(1)); // oneconsole.log(foo.getBar(2)); // twoconsole.log(foo.getBar(1)); // another oneconsole.log(foo.getBar(1)); // another one - this is last defined behavior for arg '1' so it will be repeatedconsole.log(foo.getBar(2)); // twoconsole.log(foo.getBar(2)); // two - this is last defined behavior for arg '2' so it will be repeated
Short notation:
const mockedFoo:Foo = mock(Foo);// You can specify return values as multiple thenReturn argswhen(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');const foo:Foo = instance(mockedFoo);console.log(foo.getBar(1)); // oneconsole.log(foo.getBar(1)); // twoconsole.log(foo.getBar(1)); // threeconsole.log(foo.getBar(1)); // three - last defined behavior will be repeated infinity
Possible errors:
const mockedFoo:Foo = mock(Foo);// When multiple matchers, matches same result:when(mockedFoo.getBar(anyNumber())).thenReturn('one');when(mockedFoo.getBar(3)).thenReturn('one');const foo:Foo = instance(mockedFoo);foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call
Mocking interfaces
You can mock interfaces too, just instead of passing type to mock function, set mock function generic type
Mocking interfaces requires Proxy implementation
let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)const foo: SampleGeneric<FooInterface> = instance(mockedFoo);
const foo: Foo = new Foo();const spiedFoo = spy(foo);when(spiedFoo.getBar(3)).thenReturn('one');console.log(foo.getBar(3)); // 'one'console.log(foo.getBaz()); // call to a real method