Skip to content

Commit

Permalink
feat: add asynchronous caller
Browse files Browse the repository at this point in the history
  • Loading branch information
orlandohohmeier committed Jun 10, 2018
1 parent ef3ff38 commit 4de059a
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default as AsynchronousCaller } from "./src/AsynchronousCaller";
export { default as SynchronousCaller } from "./src/SynchronousCaller";
10 changes: 10 additions & 0 deletions src/AsynchronousCaller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Callable from "./Callable";
import Caller from "./Caller";

export default class AsynchronousCaller implements Caller {
public call(thisArg: any, callable: Callable, ...args: any[]): Promise<any> {
return new Promise(resolve => setTimeout(resolve)).then(() =>
callable.call(thisArg, ...args)
);
}
}
37 changes: 37 additions & 0 deletions src/__tests__/AsynchronousCaller-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import AsynchronousCaller from "../AsynchronousCaller";
import SynchronousCaller from "../SynchronousCaller";

describe("AsynchronousCaller", () => {
const caller = new AsynchronousCaller();

it("calls the provided callable", async () => {
const callable = jest.fn();
await caller.call(null, callable);
expect(callable).toHaveBeenCalled();
});

it("passes arguments to the provided callable", async () => {
const callable = jest.fn();
await caller.call(null, callable, 1, 2, 3);
expect(callable).toHaveBeenCalledWith(1, 2, 3);
});

it("sets the `this` context to the provided value", async () => {
const context = { foo: "bar" };
await caller.call(context, function(this: { foo: string }) {
expect(this).toBe(context);
});
});

it("asynchronously calls the callable", async () => {
const callable = jest.fn();

await Promise.all([
caller.call(null, callable, "b"),
new SynchronousCaller().call(null, callable, "a")
]);

expect(callable).toHaveBeenNthCalledWith(1, "a");
expect(callable).toHaveBeenNthCalledWith(2, "b");
});
});

0 comments on commit 4de059a

Please sign in to comment.