aboutsummaryrefslogtreecommitdiffstats
path: root/tests/unit_tests/test_chrome_stubs.coffee
blob: f32de24fe71e01efdc7fbcaed6fc955f8f16499d (plain)
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
global.chrome ||= {}
global.runtime ||= {}
global.chrome.storage ||= {}

#
# This is a stub for chrome.strorage.sync for testing.
# It does what chrome.storage.sync should do (roughly), but does so synchronously.
#

global.chrome.storage.onChanged ||=
  addListener: (func) -> @func = func

  # Fake a callback from chrome.storage.sync.
  call: (key,value) ->
    chrome.runtime = { lastError: undefined }
    if @func
      @func( @mkKeyValue(key,value), 'synced storage stub' )

  mkKeyValue: (key, value) ->
    obj = {}
    obj[key] = { newValue: value }
    obj

global.chrome.storage.sync ||=
  store: {}

  set: (items,callback) ->
    chrome.runtime = { lastError: undefined }
    for own key, value of items
      @store[key] = value
    if callback
      callback()
    # Now, generate (supposedly asynchronous) notifications for listeners.
    for own key, value of items
      global.chrome.storage.onChanged.call(key,value)

  get: (keys,callback) ->
    chrome.runtime = { lastError: undefined }
    if keys == null
      keys = []
      for own key, value of @store
        keys.push key
    items = {}
    for key in keys
      items[key] = @store[key]
    # Now, generate (supposedly asynchronous) callback
    if callback
      callback items

  remove: (key,callback) ->
    chrome.runtime = { lastError: undefined }
    if key of @store
      delete @store[key]
    if callback
      callback()