summaryrefslogtreecommitdiff
path: root/public/javascripts/Fake.js
blob: bc596864d7f5a4ef943771223d9733d727829d50 (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
var Fake = (function(){
  var fake = function(){
    _stubs = [];
    this.stub = function(method){
      if(_stubs[method] === undefined) {
        _stubs[method] = new Stub(this, method);
      }
      return _stubs[method];
    };
  };
  return function(){
    return new fake();
  };
})();

var Stub = (function(){
  var stub = function(target, method){
    this.arguments = [];
    this.with = function(){
      var args = new Arguments(this, target, method, arguments);
      this.arguments.push(args);
      return args;
    };
    this.andReturn = function(return_value){
      target[method] = function(){
        return return_value;
      };
    };
    this.find_match_for = function(args){
      for (var i = 0; i < this.arguments.length; i += 1) {
        var matcher = this.arguments[i];
        if(matcher.matches(args)){
          return matcher;
        }
      }
      throw "Matcher not found.";
    };
  };
  return function(target, method){
    return new stub(target, method);
  };
})();
var Arguments = (function(){
  var Arguments = function(stub, target, method, expected_args){
    this.andReturn = function(return_value){
      this.return_value = return_value;

      target[method] = function(){
        return stub.find_match_for(arguments).return_value;
      };
    };
    this.matches = function(args){
      var result = expected_args === args;
      for (var i = 0; i < expected_args.length; i += 1) {
        if(args[i] !== expected_args[i]){
          return false;
        }
      }
      return true;
    };
  };
  return function(stub, target, method, expected_args){
    return new Arguments(stub, target, method, expected_args);
  };
})();