Skip to content

Commit

Permalink
test: testing event emitter as global event manager #134
Browse files Browse the repository at this point in the history
  • Loading branch information
4lessandrodev committed Apr 10, 2024
1 parent 548bc00 commit a92035d
Showing 1 changed file with 98 additions and 0 deletions.
98 changes: 98 additions & 0 deletions tests/core/global-events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { Aggregate, Ok, Result, Context } from "../../lib/core";
import { EventHandler } from "../../lib/types";

describe('global-events', () => {

it('user instance should dispatch global event', () => {

// ------------------
// Any Other Context

const context = Context.instance();

context.addListener('REGISTER', (user: { name: string }) => {
console.log(user);
});

// ------------------
// User Account Context

type Props = { name: string };

class User extends Aggregate<Props>{
private constructor(props: Props) {
super(props);
}

public static signUp(name: string): User {
return new User({ name });
}

public static create(props: Props): Result<User> {
return Ok(new User(props));
}
}

const user = User.signUp('Jane Doe');

context.emit('REGISTER', user.toObject());

expect(1).toBe(1);

});


it('another possibility, dispatch to global event on handler', () => {

// ------------------
// Any Other Context

const contextX = Context.instance();

contextX.addListener('SIGNUP', (arg) => {
console.log(arg);
});


// ------------------
// User Account Context

type Props = { name: string };

class User extends Aggregate<Props>{
private constructor(props: Props) {
super(props);
}

public static signUp(name: string): User {
const user = new User({ name });
user.addEvent(new SigNupEvent());
return user;
}

public static create(props: Props): Result<User> {
return Ok(new User(props));
}
}

const contextY = Context.instance();

class SigNupEvent extends EventHandler<User> {
constructor() {
super({ eventName: 'SIGNUP' })
}

dispatch(user: User): void {
contextY.emit(this.params.eventName, user.toObject());
};
}

const user = User.signUp('John Doe');

user.dispatchEvent('SIGNUP');

expect(1).toBe(1);

});

});

0 comments on commit a92035d

Please sign in to comment.