2

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

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

现在,我的问题是如何在不将它们包含在 html 页面中的情况下使模型和规范可以使用主干.js?我想保持 js 代码与 html 分离,并且能够使用 jasmine-node 运行测试

4

1 回答 1

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>
于 2012-06-10T16:58:48.607 回答