如何使用jasmine对保存的主干成功和错误响应进行单元测试

Gur*_*raj 5 jquery backbone.js jasmine jasmine-jquery jasmine-node

 onSaveEvent: function (event) {
                if (this.model !== null) {
                    var that = this;

                    this.model.save(this.model.toJSON(), {
                        success: function (model) {
                            that.model = model;
                            that.model.attributes.isDirty = false;
                        },

                        error: function (model, xhr) {
                            that.model.attributes.isDirty = true;
                        }
                    });
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

如何对模型进行单元测试,以保存Jasmine中的成功和错误响应?

Sco*_*leo 1

您可以使用Sinon.js 为您的测试创建一个假服务器。

http://sinonjs.org/

示例代码:

  describe("when saving a user model", function() {

    beforeEach(function() {
      this.server = sinon.fakeServer.create();
      this.responseBody = '{"name":"test user","id":1,"title":"tester"}';
      this.server.respondWith(
        "POST",
        "/user",
        [
          200,
          {"Content-Type": "application/json"},
          this.responseBody
        ]
      );
      this.eventSpy = sinon.spy();
    });

    afterEach(function() {
      this.server.restore();
    });

    it("should not save when name is blank", function() {
      this.user.bind("error", this.eventSpy);
      this.user.save({"name": ""});

      expect(this.eventSpy).toHaveBeenCalledOnce();    
      expect(this.eventSpy).toHaveBeenCalledWith(this.user, "cannot have a blank name");
    });

    it("should call the server", function() {
      this.user.save();
      expect(this.server.requests[0].method).toEqual("POST");
      expect(this.server.requests[0].url).toEqual("/user");
      expect(JSON.parse(this.server.requests[0].requestBody)).toEqual(this.user.attributes);
    });

  });
Run Code Online (Sandbox Code Playgroud)