dep.spec.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import Dep, { cleanupDeps } from 'core/observer/dep'
  2. describe('Dep', () => {
  3. let dep
  4. beforeEach(() => {
  5. dep = new Dep()
  6. })
  7. describe('instance', () => {
  8. it('should be created with correct properties', () => {
  9. expect(dep.subs.length).toBe(0)
  10. expect(new Dep().id).toBe(dep.id + 1)
  11. })
  12. })
  13. describe('addSub()', () => {
  14. it('should add sub', () => {
  15. dep.addSub(null)
  16. expect(dep.subs.length).toBe(1)
  17. expect(dep.subs[0]).toBe(null)
  18. })
  19. })
  20. describe('removeSub()', () => {
  21. it('should remove sub', () => {
  22. const sub = {}
  23. dep.subs.push(sub)
  24. dep.removeSub(sub)
  25. expect(dep.subs.includes(sub)).toBe(false)
  26. // nulled subs are cleared on next flush
  27. cleanupDeps()
  28. expect(dep.subs.length).toBe(0)
  29. })
  30. })
  31. describe('depend()', () => {
  32. let _target
  33. beforeAll(() => {
  34. _target = Dep.target
  35. })
  36. afterAll(() => {
  37. Dep.target = _target
  38. })
  39. it('should do nothing if no target', () => {
  40. Dep.target = null
  41. dep.depend()
  42. })
  43. it('should add itself to target', () => {
  44. Dep.target = { addDep: vi.fn() } as any
  45. dep.depend()
  46. expect(Dep.target!.addDep).toHaveBeenCalledWith(dep)
  47. })
  48. })
  49. describe('notify()', () => {
  50. it('should notify subs', () => {
  51. dep.subs.push({ update: vi.fn() })
  52. dep.notify()
  53. expect(dep.subs[0].update).toHaveBeenCalled()
  54. })
  55. })
  56. })