aboutsummaryrefslogtreecommitdiffstats
path: root/spec/RAFPlugin.js
blob: 61eed46f81dcc38e8d03726acd900b253eb8cc5d (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* globals jasmine */
/**
 * Jasmine RequestAnimationFrame: a set of helpers for testing funcionality
 * that uses requestAnimationFrame under the Jasmine BDD framework for JavaScript.
 */
function RAFPlugin (jasmine) {

  var index = 0
  var callbacks = []

  function MockRAF () {
    this.nextTime = 0

    var _this = this

    /**
    * Mock for window.requestAnimationFrame
    */
    this.mockRAF = function (fn) {
      if (typeof fn !== 'function') {
        throw new Error('You should pass a function to requestAnimationFrame')
      }

      const i = index++
      callbacks[i] = fn

      return i
    }

    /**
    * Mock for window.cancelAnimationFrame
    */
    this.mockCAF = function (requestID) {
      callbacks.splice(requestID, 1)
    }

    this.mockPerf = {
      now: function () {
        return _this.nextTime
      }
    }

    /**
    * Install request animation frame mocks.
    */
    this.install = function (global) {
      _this.realRAF = global.requestAnimationFrame
      _this.realCAF = global.cancelAnimationFrame
      _this.realPerf = global.performance
      global.requestAnimationFrame = _this.mockRAF
      global.cancelAnimationFrame = _this.mockCAF
      global.performance = _this.mockPerf
    }

    /**
    * Uninstall request animation frame mocks.
    */
    this.uninstall = function (global) {
      global.requestAnimationFrame = _this.realRAF
      global.cancelAnimationFrame = _this.realCAF
      global.performance = _this.realPerf
      _this.nextTime = 0
      callbacks = []
    }

    /**
    * Simulate animation frame readiness.
    */
    this.tick = function (dt) {
      _this.nextTime += (dt || 1)

      var fns = callbacks; var fn; var i

      callbacks = []
      index = 0

      for (i in fns) {
        fn = fns[i]
        fn(_this.nextTime)
      }
    }
  }

  jasmine.RequestAnimationFrame = new MockRAF()
}

RAFPlugin(jasmine)