Blog

Blog

PHODAL

Backbone Collection Sinon测试之fake server

实践了一下怎么用sinon去fake server,还没用respondWith,于是写一下。

这里需要用到sinon框架来测试。

Sinon fake server

当我们fetch的时候,我们就可以返回我们想要fake的结果。

    var data = {"id":1,"name":"Rice","type":"Good","price":12,"quantity":1,"description":"Made in China"};
beforeEach(function() {
    this.server = sinon.fakeServer.create();
    this.rices = new Rices();
    this.server.respondWith(
        "GET",
        "http://localhost:8080/all/rice",
        [
            200,
            {"Content-Type": "application/json"},
            JSON.stringify(data)
        ]
    );
});

于是在afterEach的时候,我们需要恢复这个server。

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

接着写一个jasmine测试来测试

describe("Collection Test", function() {
    it("should get data from the url", function() {
        this.rices.fetch();
        this.server.respond();
        var result = JSON.parse(JSON.stringify(this.rices.models[0]));
        expect(result["id"])
            .toEqual(1);
        expect(result["price"])
            .toEqual(12);
        expect(result)
            .toEqual(data);
    });
});

关于我

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

微信公众号(Phodal)

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

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

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

开源深度爱好者

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

联系我: h@phodal.com

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

标签