如何正确使用RequireJS?

时间:2015-04-23 10:06:29

标签: javascript testing requirejs jasmine

我需要测试一个JavaScript项目。有几个模块描述,但当我尝试加载它们时出错了。

define([
  'core/BaseModel'
],

function (BaseModel) {
  var MessageModel = BaseModel.extend({
    defaults: {
      messageType: "Advertisment",
      receiver: "me",
      title: "Title",
      heading_1: "Heading1",
      heading_2: "Heading2"
    },

    url: function () {
      var base = this.apipath + '/companies/';
      if (this.isNew()) return base;
      return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
    }
  });

  return MessageModel;
});

要加载模块,我这样做:

var message;
beforeAll(function(done){
    require(['../../../public/js/app/models/Message'], function(Message){
        message = Message;
        done();
    });
});

现在消息未定义但是当我测试是否定义了message.defaults或message.url时,这会失败。那里有什么问题?

2 个答案:

答案 0 :(得分:0)

鉴于 ../../../ public / js / app / models / Message 对应MessageModel,您想要的是什么做的是:

var Message = require('../../../public/js/app/models/Message');

并创建一个新实例:var m = new Message();

希望这有帮助。

答案 1 :(得分:-1)

我找到了一个适用于这个确切示例的解决方案。而不是

message = Message;

我写

message = new Message();

但我使用不同的模块完全相同,它只会产生超时错误并保持未定义:

var router;

beforeAll(function(done){
    require(['../../../public/js/app/routers/DesktopRouter'], function(Router){
        router = new Router();
        done();
    });
});

其定义是:

define(["jquery", "underscore", "backbone", "core/BaseRouter", "models/Session", "i18n!locales",

  "views/NavbarView",
  "views/LoginView",
  'views/SidebarView',
  'views/FooterView',
  'views/VehicleSidebarView',
  "views/DashboardView",
  "views/CompaniesView",
  "views/WorkshopsView",
  "views/VehiclesView",
  "views/UsersView",
  "views/AddVehicleView",
  "views/VehicleTripsView",
  "views/VehicleDataView",
  "views/VehicleServiceView",
  "views/VehicleErrorsView",
  "views/MessageInboxView",
  "views/AddUserView",
  "views/EditUserView",
  "views/EditProfileView",
  "views/AppDownloadView",
  "views/BlockBrowserView"
],

function($, _, Backbone, BaseRouter, Session, i18n,

       NavbarView,
       LoginView,
       SideBarView,
       FooterView,
       VehicleSidebarView,
       DashboardView,
       CompaniesView,
       WorkshopsView,
       VehiclesView,
       UsersView,
       AddVehicleView,
       VehicleTripsView,
       VehicleDataView,
       VehicleServiceView,
       VehicleErrorsView,
       MessageInboxView,
       AddUserView,
       EditUserView,
       EditProfileView,
       AppDownloadView,
       BlockBrowserView
) {

var DesktopRouter = BaseRouter.extend({

  initialize: function () {
.....