Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

functions mock feature #102

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/ts-mockito.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T = (...args: any[]) => 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<T>(instanceToSpy: T): T {
return new Spy(instanceToSpy).getMock();
}
Expand Down Expand Up @@ -128,6 +147,7 @@ export function objectContaining(expectedValue: Object): Matcher {
export default {
spy,
mock,
mockFn,
verify,
when,
instance,
Expand Down
58 changes: 58 additions & 0 deletions test/mocking.func.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
});