domain-event.spec.ts raw
1 import { DomainEvent, AggregateRoot } from './domain-event';
2
3 // Concrete implementation for testing
4 class TestEvent extends DomainEvent {
5 readonly eventType = 'test.event';
6
7 constructor(readonly testData: string) {
8 super();
9 }
10 }
11
12 class TestAggregate extends AggregateRoot {
13 doSomething(data: string): void {
14 this.addDomainEvent(new TestEvent(data));
15 }
16 }
17
18 describe('DomainEvent', () => {
19 describe('base properties', () => {
20 it('should have occurredAt timestamp', () => {
21 const before = new Date();
22 const event = new TestEvent('test');
23 const after = new Date();
24
25 expect(event.occurredAt.getTime()).toBeGreaterThanOrEqual(before.getTime());
26 expect(event.occurredAt.getTime()).toBeLessThanOrEqual(after.getTime());
27 });
28
29 it('should have unique eventId', () => {
30 const event1 = new TestEvent('test1');
31 const event2 = new TestEvent('test2');
32
33 expect(event1.eventId).not.toEqual(event2.eventId);
34 });
35
36 it('should have eventType from subclass', () => {
37 const event = new TestEvent('test');
38
39 expect(event.eventType).toEqual('test.event');
40 });
41 });
42 });
43
44 describe('AggregateRoot', () => {
45 describe('domain events', () => {
46 it('should collect domain events', () => {
47 const aggregate = new TestAggregate();
48
49 aggregate.doSomething('first');
50 aggregate.doSomething('second');
51
52 const events = aggregate.pullDomainEvents();
53
54 expect(events.length).toBe(2);
55 expect((events[0] as TestEvent).testData).toEqual('first');
56 expect((events[1] as TestEvent).testData).toEqual('second');
57 });
58
59 it('should clear events after pulling', () => {
60 const aggregate = new TestAggregate();
61 aggregate.doSomething('test');
62
63 aggregate.pullDomainEvents();
64 const secondPull = aggregate.pullDomainEvents();
65
66 expect(secondPull.length).toBe(0);
67 });
68
69 it('should preserve event order', () => {
70 const aggregate = new TestAggregate();
71
72 aggregate.doSomething('1');
73 aggregate.doSomething('2');
74 aggregate.doSomething('3');
75
76 const events = aggregate.pullDomainEvents();
77
78 expect(events.map(e => (e as TestEvent).testData)).toEqual(['1', '2', '3']);
79 });
80 });
81 });
82