Skip to content

Instantly share code, notes, and snippets.

@kazu69
Created May 22, 2012 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu69/2769620 to your computer and use it in GitHub Desktop.
Save kazu69/2769620 to your computer and use it in GitHub Desktop.
sinon.jsとbackbonejsのsimpleなSpyTest
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Backbone + sinon simple tests</title>
<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src='http://documentcloud.github.com/underscore/underscore-min.js'></script>
<script type="text/javascript" src='http://documentcloud.github.com/backbone/backbone.js'></script>
<script type="text/javascript" src='http://sinonjs.org/releases/sinon-1.3.4.js'></script>
<script src="https://raw.github.com/douglascrockford/JSON-js/master/json2.js" type="text/javascript"></script>
<script type="text/javascript">
var Foo = {
name : 'My name is Foo',
hey : function() { console.log(this.name);}
}
// spy clled Foo.hey() is fired
var spy = sinon.spy(Foo,'hey');
var Bar = {};
_.extend(Bar,Backbone.Events);
Bar.name = "My name is Bar";
Bar.bind("bar", Foo.hey);
Bar.trigger("bar");
console.log(spy.called) // -> true
var Model = Backbone.Model.extend({
initialize : function(){console.log('initialize')},
validate : function(attrs){return 'error'},
url : "http://jsfiddle.net/echo/jsonp/"
});
var model = new Model();
var spy = sinon.spy();
model.bind("error", spy);
model.save({hoo:'bar'});
console.log(spy.called); // -> true
var server = sinon.fakeServer.create();
var model = new Model();
model.fetch();
var fixtures = {
Response: {
valid: { // response starts here
"status": "OK",
"version": "1.0",
"response": {
"res": [
{
"response": "this is response"
}
]
}
}
}
};
fixture = this.fixtures.Response.valid;
server.respondWith(
"GET",
"/response",
[
200,
{"Content-Type": "application/json"},
JSON.stringify(fixture)
]
);
console.log(server.requests.length); // -> 1
console.log(fixture.response.res.length) // -> 1
console.log(server.requests[0].method) // -> GET
console.log(server.requests[0].url) // -> http://jsfiddle.net/echo/jsonp/
server.restore();
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment