Lorraine Bernard
Lorraine Bernard

Reputation: 13420

How should I write the spec file using requireJs?

I have a model which looks like this:

//myModel.js
define([], function () {
    var MyModel = Backbone.Model.extend({
        // my code
    });
    return MyModel
});

Then If I want to write a spec for this model how should I load the model using requireJs?

I did try the following:

//myModel.spec.js
define([
    "js/models/myModel",
], function (MyModel) {
    describe("My model", function()
    {
        beforeEach(function () 
        {
            this.myModel = new MyModel({
                name: "my title"
            });
        });
    });
});

Is this the right way?

Upvotes: 4

Views: 912

Answers (1)

Dave Cadwallader
Dave Cadwallader

Reputation: 1751

Yes, this is correct. The great thing about using RequireJS for testing is that you're forced to declare all your test dependencies in your define block. By definition, a unit test should only be testing one thing. So if you have multiple dependencies in one test, it's a code smell that you're not doing real "unit testing" at all.

Ideally, the only dependency should be the file which is under test. If that file has any dependencies, itself, such as server-side services, or complex asynchronous APIS, you can use stubs and mocks to simulate them. Check out SinonJS for a great stubbing/mocking library.

Upvotes: 2

Related Questions