我想测试我的控制器,它对我的后端进行 ajax 调用。所以我想用茉莉和诗乃。为了用 sinon 伪造我的后端服务器,我尝试了这样的方法:
describe("fake server", function() {
var server;
beforeEach(function() {
this.server = sinon.fakeServer.create();
});
afterEach(function() {
this.server.restore();
});
it("calls callback with deserialized data", function () {
var callback = sinon.spy();
this.server.respondWith("GET", "/comments/1",
[200, {"Content-Type": "application/json"},
'{"comment":{"id":1,"title":"ducks and ducks"}}']);
commentController = App.CommentController.create();
//commentController.bind('getComment', callback);
commentController.getComment();
this.server.respond();
expect(callback.called).toBeTruthy();
expect(callback.getCall(0).args[0].attributes)
.toEqual({
id: "1",
title: "ducks and ducks"
});
});
});
我的控制器如下所示:
App.CommentController = Ember.Controller.extend({
getComment: function() {
$.ajax({
url: 'http://myapi/comments/' + id,
//...
error: function(jqXHR, textStatus){
this.set("error",true);
//do something
},
success: function(data) {
this.set("error",false);
//do something else
}
});
}
});
有人可以告诉我如何运行它吗?