Skip to content

Commit

Permalink
We have event observer with a test
Browse files Browse the repository at this point in the history
  • Loading branch information
David-Else committed Feb 20, 2020
1 parent 888d065 commit 3134c8b
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 40 deletions.
8 changes: 7 additions & 1 deletion deps.ts
@@ -1 +1,7 @@
export { assertEquals, assertThrowsAsync } from "testing/asserts.ts";
/**
* assert() - Expects a boolean value, throws if the value is false.
* assertEquals() - Uses the equal comparison and throws if the actual and expected are not equal.
* assertStrictEq() - Compares actual and expected strictly, therefore for non-primitives the values must reference the same
*/

export { assert, assertEquals, assertStrictEq } from "testing/asserts.ts";
18 changes: 18 additions & 0 deletions src/EventObserver.ts
@@ -0,0 +1,18 @@
// https://www.sitepoint.com/javascript-design-patterns-observer-pattern/
export class EventObserver {
constructor(public observers = [] as any) {}

subscribe(fn: any) {
this.observers.push(fn);
}

unsubscribe(fn: any) {
this.observers = this.observers.filter(
(subscriber: any) => subscriber !== fn
);
}

broadcast(data: any) {
this.observers.forEach((subscriber: any) => subscriber(data));
}
}
5 changes: 4 additions & 1 deletion src/new-test-pattern.ts
@@ -1,3 +1,4 @@
import { EventObserver } from "../src/EventObserver";
import { Vector2, vectors } from "./utilities/vectors";

interface Delegate {
Expand Down Expand Up @@ -93,7 +94,9 @@ class DirectTowardsable implements Delegate {
);
}
}

/**
* this is not a delegate... it is shared state that can be pushed inside a delegate
*/
class Positionable {
constructor(
public position: Vector2,
Expand Down
37 changes: 0 additions & 37 deletions test/loader_test.ts

This file was deleted.

40 changes: 40 additions & 0 deletions test/new-test-patterns_test.ts
@@ -0,0 +1,40 @@
import { assertEquals, assert } from "../deps.ts";
import { EventObserver } from "../src/EventObserver.ts";
/**
* SUBSCRIBE UNSUBSCRIBE
*/
Deno.test({
name: "SUBSCRIBE UNSUBSCRIBE",
fn(): void {
// Arrange
const observer = new EventObserver();
const fn = () => {};
observer.subscribe(fn);

// Act
observer.unsubscribe(fn);

// Assert
assertEquals(observer.observers.length, 0);
}
});

/**
* BROADCAST
*/
Deno.test({
name: "BROADCAST",
fn(): void {
// Arrange
const observer = new EventObserver();
let subscriberHasBeenCalled = false;
const fn = data => (subscriberHasBeenCalled = data);
observer.subscribe(fn);

// Act
observer.broadcast(true);

// Assert
assert(subscriberHasBeenCalled);
}
});
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -9,6 +9,6 @@
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"include": ["src/**/*", "test/**/*"],
"exclude": ["node_modules"]
}

0 comments on commit 3134c8b

Please sign in to comment.