about summary refs log tree commit diff
path: root/__tests__/state/models/link-metas-view.test.ts
blob: 0e5fb8da579a8ecfede34cf726a544d64d2566df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {RootStoreModel} from '../../../src/state/models/root-store'
import {LinkMetasViewModel} from '../../../src/state/models/link-metas-view'
import * as LinkMetaLib from '../../../src/lib/link-meta'
import {LikelyType} from './../../../src/lib/link-meta'
import {sessionClient, SessionServiceClient} from '@atproto/api'
import {DEFAULT_SERVICE} from '../../../src/state'

describe('LinkMetasViewModel', () => {
  let viewModel: LinkMetasViewModel
  let rootStore: RootStoreModel

  const getLinkMetaMockSpy = jest.spyOn(LinkMetaLib, 'getLinkMeta')
  const mockedMeta = {
    title: 'Test Title',
    url: 'testurl',
    likelyType: LikelyType.Other,
  }

  beforeEach(() => {
    const api = sessionClient.service(DEFAULT_SERVICE) as SessionServiceClient
    rootStore = new RootStoreModel(api)
    viewModel = new LinkMetasViewModel(rootStore)
  })

  afterAll(() => {
    jest.clearAllMocks()
  })

  describe('getLinkMeta', () => {
    it('should return link meta if it is cached', async () => {
      const url = 'http://example.com'

      viewModel.cache.set(url, mockedMeta)

      const result = await viewModel.getLinkMeta(url)

      expect(getLinkMetaMockSpy).not.toHaveBeenCalled()
      expect(result).toEqual(mockedMeta)
    })

    it('should return link meta if it is not cached', async () => {
      getLinkMetaMockSpy.mockResolvedValueOnce(mockedMeta)

      const result = await viewModel.getLinkMeta(mockedMeta.url)

      expect(getLinkMetaMockSpy).toHaveBeenCalledWith(rootStore, mockedMeta.url)
      expect(result).toEqual(mockedMeta)
    })

    it('should cache the link meta if it is successfully returned', async () => {
      getLinkMetaMockSpy.mockResolvedValueOnce(mockedMeta)

      await viewModel.getLinkMeta(mockedMeta.url)

      expect(viewModel.cache.get(mockedMeta.url)).toEqual(mockedMeta)
    })

    it('should not cache the link meta if it fails to return', async () => {
      const url = 'http://example.com'
      const error = new Error('Failed to fetch link meta')
      getLinkMetaMockSpy.mockRejectedValueOnce(error)

      try {
        await viewModel.getLinkMeta(url)
        fail('Error was not thrown')
      } catch (e) {
        expect(e).toEqual(error)
        expect(viewModel.cache.get(url)).toBeUndefined()
      }
    })
  })
})