test-container.spec.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { describe, expect, it, vi } from "vitest"
  2. import { TestContainer } from "../lib/testing"
  3. import { Service } from "../lib/service"
  4. import { ContainerEvent } from "../lib/container"
  5. class TestServiceA extends Service {
  6. public static ID = "TestServiceA"
  7. public test() {
  8. return "real"
  9. }
  10. }
  11. class TestServiceB extends Service {
  12. public static ID = "TestServiceB"
  13. // declared public to help with testing
  14. public readonly serviceA = this.bind(TestServiceA)
  15. public test() {
  16. return this.serviceA.test()
  17. }
  18. }
  19. describe("TestContainer", () => {
  20. describe("bindMock", () => {
  21. it("returns the fake service defined", () => {
  22. const container = new TestContainer()
  23. const fakeService = {
  24. test: () => "fake",
  25. }
  26. const result = container.bindMock(TestServiceA, fakeService)
  27. expect(result).toBe(fakeService)
  28. })
  29. it("new services bound to the container get the mock service", () => {
  30. const container = new TestContainer()
  31. const fakeServiceA = {
  32. test: () => "fake",
  33. }
  34. container.bindMock(TestServiceA, fakeServiceA)
  35. const serviceB = container.bind(TestServiceB)
  36. expect(serviceB.serviceA).toBe(fakeServiceA)
  37. })
  38. it("container emits SERVICE_BIND event", () => {
  39. const container = new TestContainer()
  40. const fakeServiceA = {
  41. test: () => "fake",
  42. }
  43. const serviceFunc = vi.fn<[ContainerEvent, void]>()
  44. container.getEventStream().subscribe((ev) => {
  45. serviceFunc(ev)
  46. })
  47. container.bindMock(TestServiceA, fakeServiceA)
  48. expect(serviceFunc).toHaveBeenCalledOnce()
  49. expect(serviceFunc).toHaveBeenCalledWith(<ContainerEvent>{
  50. type: "SERVICE_BIND",
  51. boundeeID: TestServiceA.ID,
  52. bounderID: undefined,
  53. })
  54. })
  55. it("throws if service already bound", () => {
  56. const container = new TestContainer()
  57. const fakeServiceA = {
  58. test: () => "fake",
  59. }
  60. container.bindMock(TestServiceA, fakeServiceA)
  61. expect(() => {
  62. container.bindMock(TestServiceA, fakeServiceA)
  63. }).toThrowError(
  64. "Service 'TestServiceA' already bound to container. Did you already call bindMock on this ?"
  65. )
  66. })
  67. })
  68. })