memoize.spec.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { h, Component, memoize, nextTick } from '../src'
  2. import { renderInstance, serialize } from '@vue/runtime-test'
  3. describe('memoize', () => {
  4. it('should work', async () => {
  5. class App extends Component {
  6. count = 1
  7. render() {
  8. return h('div', [
  9. this.count,
  10. this.count % 2
  11. ? memoize(() => h('div', `A` + this.count), this, 0)
  12. : null,
  13. memoize(() => h('div', `B` + this.count), this, 1)
  14. ])
  15. }
  16. }
  17. const app = await renderInstance(App)
  18. expect(serialize(app.$el)).toBe(`<div>1<div>A1</div><div>B1</div></div>`)
  19. app.count++
  20. await nextTick()
  21. expect(serialize(app.$el)).toBe(`<div>2<div>B1</div></div>`)
  22. app.count++
  23. await nextTick()
  24. // test remounting a memoized tree
  25. expect(serialize(app.$el)).toBe(`<div>3<div>A1</div><div>B1</div></div>`)
  26. })
  27. it('should invalidate based on keys', async () => {
  28. class App extends Component {
  29. foo = 1
  30. bar = 1
  31. render() {
  32. return memoize(() => h('div', this.foo + this.bar), this, 0, [this.bar])
  33. }
  34. }
  35. const app = await renderInstance(App)
  36. expect(serialize(app.$el)).toBe(`<div>2</div>`)
  37. app.foo++
  38. await nextTick()
  39. // should not update
  40. expect(serialize(app.$el)).toBe(`<div>2</div>`)
  41. app.bar++
  42. await nextTick()
  43. // should update now
  44. expect(serialize(app.$el)).toBe(`<div>4</div>`)
  45. })
  46. })