diff --git a/src/ts-mockito.ts b/src/ts-mockito.ts index 552c719..4e18745 100644 --- a/src/ts-mockito.ts +++ b/src/ts-mockito.ts @@ -29,6 +29,25 @@ import {MethodToStub} from "./MethodToStub"; import {Mocker} from "./Mock"; import {Spy} from "./Spy"; +class MockFn { + public call(...args: any[]): any {} +} + +export function mockFn any>(cb?: T): T { + const fnMock = mock(MockFn); + const mockInstance = instance(fnMock); + function call(...args: any[]) { + return mockInstance.call(...args); + } + + const mocker = fnMock.call; + + (mocker as any).__tsmockitoInstance = call; + (mocker as any).__tsmockitoMocker = (fnMock as any).__tsmockitoMocker; + + return mocker as any; +} + export function spy(instanceToSpy: T): T { return new Spy(instanceToSpy).getMock(); } @@ -128,6 +147,7 @@ export function objectContaining(expectedValue: Object): Matcher { export default { spy, mock, + mockFn, verify, when, instance, diff --git a/test/mocking.func.spec.ts b/test/mocking.func.spec.ts new file mode 100644 index 0000000..2e74c5f --- /dev/null +++ b/test/mocking.func.spec.ts @@ -0,0 +1,58 @@ +import {MethodToStub} from "../src/MethodToStub"; +import {capture, instance, mock, mockFn, reset, verify, when} from "../src/ts-mockito"; + +describe("mocking", () => { + describe("mocking function", () => { + let mockedFoo; + let foo; + + it("does create function mock", () => { + // given + + // when + mockedFoo = mockFn(); + + // then + expect(mockedFoo() instanceof MethodToStub).toBe(true); + }); + + it("does when", () => { + // given + mockedFoo = mockFn(); + foo = instance(mockedFoo); + + // when + when(mockedFoo("foo")).thenReturn(42); + + // then + expect(foo("foo")).toBe(42); + }); + + it("does capture", () => { + // given + mockedFoo = mockFn(); + foo = instance(mockedFoo); + foo(42); + // when + const [arg] = capture(mockedFoo).last(); + expect(arg).toBe(42); + }); + + it("does verify", () => { + // given + mockedFoo = mockFn(); + foo = instance(mockedFoo); + foo(42); + verify(mockedFoo(42)).once(); + }); + + it("does reset", () => { + // given + mockedFoo = mockFn(); + foo = instance(mockedFoo); + when(mockedFoo("foo")).thenReturn(41); + reset(mockedFoo); + expect(foo("foo")).toBe(null); + }); + }); +});