包括Jasmine规范中的backbone.js

时间:2012-06-07 10:51:50

标签: javascript unit-testing backbone.js jasmine

我对backbone.js(以及一般的JavaScript)很新,我正在尝试使用Jasmine对模型进行单元测试(我正在使用jasmine-node)。我的目录结构如下:

project/
      src/models/mymodel.js
      spec/mymodel.spec.js
      lib/backbone-min.js

现在,我的问题是如何让backbone.js可用于模型和规范而不将它们包含在html页面中?我想保持js代码与html解耦,只能用jasmine-node运行测试

1 个答案:

答案 0 :(得分:0)

是的,通过使用node.js主干(和下划线)模块,您可以在必要时在模型中使用它们,就像这样。

<强> /models/car.js

var args = typeof exports !== 'undefined' ? [exports, require('Backbone')] : [window, window.Backbone];

(function (exports, backbone){

    exports.Car = backbone.Model.extend({
        onHornPress: function () {
            return 'HONK';
        }
    });

}).apply(undefined, args);

<强> /specs/car.spec.js

var Backbone = require('Backbone'),
    Car = require('../models/car.js').Car;

describe("when the horn is pressed", function(){
    var car;

    beforeEach(function(){
        car = new Car();
    });

    it("should honk.", function(){
        var result = car.onHornPress();
        expect(result).toEqual('HONK');
    });

});

<强> /myapp.html

<html>
<head>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
    <script type="text/javascript" src="models/car.js"></script>
</head>
<body>
<script type="text/javascript">

    var car = new Car();

    console.log(car.onHornPress());

</script>
</body>
</html>