Blog

Blog

PHODAL

Requirejs Backbone Collection 测试

在一点点慢慢地写一个简单的SPA应用,在这样的一个过程里,我们也不得不写一些测试以方便重构。

Backbone Collection

Bacbkbone主要由三部分组成

  1. model:创建数据,进行数据验证,销毁或者保存到服务器上。

  2. collection:可以增加元素,删除元素,获取长度,排序,比较等一系列工具方法,说白了就是一个保存 models的集合类。

  3. view:绑定html模板,绑定界面元素的事件,初始的渲染,模型值改变后的重新渲染和界面元素的销毁等。

于是我们简单地定义了一个Model以及一个Collection

define(['backbone'], function(Backbone) {
    var RiceModel = Backbone.Model.extend({});
    var Rices = Backbone.Collection.extend({
        model: RiceModel,
        url: 'http://localhost:8080/all/rice',
        parse: function (data) {
            return data;
        }
    });
    return Rices;
});

用来获取数据,接着我们便可以创建一个测试,测试代码如下

define([
    'sinon',
    'js/Model/Rice_Model'
], function( sinon, Rices) {
    'use strict';

    beforeEach(function() {
        this.server = sinon.fakeServer.create();
        this.rices = new Rices();

    });

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

    describe("Collection Test", function() {
        it("should request the url and fetch", function () {
            this.rices.fetch();
            expect(this.server.requests.length)
                .toEqual(1);
            expect(this.server.requests[0].method)
                .toEqual("GET");
            expect(this.server.requests[0].url)
                .toEqual("http://localhost:8080/all/rice");
        });

    });
});

在这里我们用sinon fake了一个简单的server

this.server = sinon.fakeServer.create();

这样我们就可以在fetch的时候mock一个response,在这时我们就可以测试这里的URL是不是我们想要的URL。

            this.rices.fetch();
            expect(this.server.requests.length)
                .toEqual(1);
            expect(this.server.requests[0].method)
                .toEqual("GET");
            expect(this.server.requests[0].url)
                .toEqual("http://localhost:8080/all/rice");

这样我们便可以完成一个简单地测试的书写。

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签