eventBus.test.ts 992 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { EventBus } from "./eventBus";
  2. declare global {
  3. interface EventMapper {
  4. "": any;
  5. }
  6. }
  7. describe("eventBus", () => {
  8. const MockEvent: any = test;
  9. test("事件订阅", () => {
  10. const bus = new EventBus();
  11. const fn = jest.fn();
  12. const disposer = bus.on(MockEvent, fn);
  13. bus.emit(MockEvent, "foo");
  14. expect(fn).lastCalledWith("foo");
  15. disposer();
  16. bus.emit(MockEvent, "bar");
  17. expect(fn).toHaveBeenCalledTimes(1);
  18. });
  19. test("单次事件订阅", () => {
  20. const bus = new EventBus();
  21. const fn = jest.fn();
  22. bus.once(MockEvent, fn);
  23. bus.emit(MockEvent, "foo");
  24. bus.emit(MockEvent, "bar");
  25. expect(fn).lastCalledWith("foo");
  26. expect(fn).toHaveBeenCalledTimes(1);
  27. });
  28. test("新增订阅者", () => {
  29. const bus = new EventBus();
  30. const fn = jest.fn();
  31. bus.onSubscriber(MockEvent, (listener) => {
  32. listener("foo");
  33. });
  34. bus.on(MockEvent, fn);
  35. expect(fn).lastCalledWith("foo");
  36. });
  37. });