【问题标题】:Mocha run rendr collection ajax unit testMocha 运行 rendr 集合 ajax 单元测试
【发布时间】:2015-06-23 08:48:47
【问题描述】:

我尝试使用 rendr(backbone in client&server) 创建一个 webapp 并尝试实现一些单元测试。

有没有办法在 mocha 中运行集合提取单元测试? 我想用 sinon-chai 在 mocha 中模拟 ajax 请求。但是当我尝试以这种方式存根 $"ajax" 时会发生错误,

var chai = require("chai");
var rekuire = require("rekuire");
var sinon = require("sinon");
var $ = require("jquery"); //because this is node-jquery, we don't have ajax function.
chai.use(require("sinon-chai"));

require("chai").should();
require("mocha-sinon");

var Books = rekuire("app/collections/books");

describe("Books interaction with REST API", function() {
    it("should load using the API", function(){
        //TypeError: Cannot stub non-existent own property ajax
        this.ajax_stub = this.sinon.stub($, "ajax").yieldsTo("success", [
            {
                count: 20,
                "books": [
                    {
                        title: "Google1",
                        author: ["author1", "author2"]
                    },
                    {
                        title: "Google2",
                        author: ["author3", "author4"]
                    }
                ]
            }
        ]);
        this.books = Books.fetch();
        this.books.should.have.length(2);
        this.ajax_stub.restore();
    });
}); 

我的问题是,当我们在 mocha 中运行单元测试时,有没有办法存根 $.ajax 函数?

【问题讨论】:

    标签: javascript backbone.js mocha.js rendr


    【解决方案1】:

    对于渲染:

    测试存在一些问题。模型/集合获取实际上使用 async.parallel,而不是 $.ajax。

    另外,我不建议专门测试 .fetch,除非您要覆盖它。此功能已经在 Rendr 内部进行了测试,因此该测试不会为您提供太多实用性。如果您要覆盖,我建议只删除 collection.fetch 函数,并使用该 yield 而不是 $

    【讨论】:

    • 你的意思是我们不需要测试collection fetch函数?集合从服务器获取数据后,有一个钩子来预解析数据。我想实施一些单元测试以确保它正常工作。
    • 您应该能够单独测试该功能。例如,只需调用parse 函数,而不是让它运行所有的前/后处理。
    • 得到它。谢谢你的帮助。 :)
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2018-12-02
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多