0

I try to use rendr(backbone in client&server) to create a webapp and try to implemented some unit test.

Is there a way to run collection fetch unit test in mocha? I want to use sinon-chai to mock ajax request in mocha. But Error happen when I try to stub $ "ajax" in this way,

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();
    });
}); 

My question is, is there a way to stub $.ajax function when we run unit test in mocha?

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31

1 Answers1

1

For rendr:

There are a few issues with the test. Model / collection fetch actually uses async.parallel, not $.ajax.

Also, I wouldn't recommending specifically testing .fetch unless you're overriding it. This function is already tested inside of Rendr itself, so the test won't give you much utility. If you're overriding, I would suggest just stubbing out the collection.fetch function, and have that yield instead of $.

  • You mean we do not need to test collection fetch function? After the collection fetch the data from server, there is a hook to pre parse the data. I want to implement some unit test to make sure it is working. – Tyler.z.yang Jun 26 '15 at 00:30
  • You should be able to test that function in isolation. Rather than having it run through all of the pre / post processing, just invoke the `parse` function for example. – user1775725 Jun 26 '15 at 21:27
  • Get it. Thx for your help. : ) – Tyler.z.yang Jun 27 '15 at 06:39