service.spec.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { describe, expect, it, vi } from "vitest"
  2. import { Service, Container } from "../lib/main"
  3. class TestServiceA extends Service {
  4. public static ID = "TestServiceA"
  5. }
  6. class TestServiceB extends Service<"test"> {
  7. public static ID = "TestServiceB"
  8. // Marked public to allow for testing
  9. public readonly serviceA = this.bind(TestServiceA)
  10. public emitTestEvent() {
  11. this.emit("test")
  12. }
  13. }
  14. describe("Service", () => {
  15. describe("constructor", () => {
  16. it("throws an error if the service is initialized without a container", () => {
  17. expect(() => new TestServiceA()).toThrowError(
  18. "Tried to initialize service with no container (ID: TestServiceA)"
  19. )
  20. })
  21. })
  22. describe("bind", () => {
  23. it("correctly binds the dependency service using the container", () => {
  24. const container = new Container()
  25. const serviceA = container.bind(TestServiceA)
  26. const serviceB = container.bind(TestServiceB)
  27. expect(serviceB.serviceA).toBe(serviceA)
  28. })
  29. })
  30. describe("getContainer", () => {
  31. it("returns the container the service is bound to", () => {
  32. const container = new Container()
  33. const serviceA = container.bind(TestServiceA)
  34. // @ts-expect-error getContainer is a protected member, we are just using it to help with testing
  35. expect(serviceA.getContainer()).toBe(container)
  36. })
  37. })
  38. describe("getEventStream", () => {
  39. it("returns the valid event stream of the service", () => {
  40. const container = new Container()
  41. const serviceB = container.bind(TestServiceB)
  42. const serviceFunc = vi.fn()
  43. serviceB.getEventStream().subscribe(serviceFunc)
  44. serviceB.emitTestEvent()
  45. expect(serviceFunc).toHaveBeenCalledOnce()
  46. expect(serviceFunc).toHaveBeenCalledWith("test")
  47. })
  48. })
  49. })