0

我有一个模型可以通过 ember-data rest 适配器保存到我的服务器。

如何通过存根或模拟 ember-data 的提交功能来测试数据是否正确发送并返回到服务器,而无需重新测试 ember-data 已经测试过的内容?

最好是茉莉花!

4

1 回答 1

1

在单元测试中,您永远不应该使用真正的客户端服务器通信。通常你会模拟浏览器的 XMLHttpRequest 实现。

有很多工具,比如jasmine-fake-ajaxsinonjs。两者都覆盖浏览器的 XHR 实现并模拟服务器。因此,您可以设置路线以及应该返回的内容。两者都可以非常精细地调整,因此您可以检查是否为类型、内容类型或设置 http 响应代码。

{
    setUp: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    tearDown: function () {
        this.xhr.restore();
    },

    "test should fetch comments from server" : function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        assert(callback.calledWith([{ id: 12, comment: "Hey there" }]));
    }
}  
于 2012-08-02T20:42:57.523 回答