node.js - 在 Node js 中使用 mocha 测试主干 js

标签 node.js backbone.js requirejs mocha.js

我有一个nodejs应用程序,它具有使用backbonejs和requirejs构建的客户端代码。 我想使用 mocha 在我的 Nodejs 服务器上测试客户端代码。

我的 Mocha 测试文件: 测试/view.coffee

requirejs = require 'requirejs'
global.define = requirejs

requirejs.config
  nodeRequire: require
  baseUrl: '../public/javascripts/libs/'
  paths:
    jquery: "jquery"
    Underscore: "underscore"
    Backbone: "backbone"
  shim:
    'jquery':
      exports: '$'
    'Underscore':
      exports: '_'
    'Backbone':
      deps: ['jquery', 'Underscore']
      exports: 'Backbone'

requirejs ['../public/javascripts/views/test_view'], (TestView) ->
  describe 'TestView', ->
    view = new TestView()

待测试的Backbonejs文件: 公共(public)/javascripts/views/test_view.coffee

define [
  'Backbone'
], (Backbone) ->
  class TestView extends Backbone.View
    initialize: ->
      ...
  TestView

在 public/javascripts/libs 中,我有 jquery、backbone 和 underscore 的缩小版(不是 AMD)。

当我运行测试时,我收到以下错误消息:

Error: Calling node's require("../public/javascripts/views/test_view")
failed with error: Error: Calling node's require("Underscore")
failed with error: Error: Cannot find module 'Underscore'
  at /node_modules/requirejs/bin/r.js:2262:27

不知何故,test/view.coffee 中 requirejs.config 的 paths 属性未被读取。 如果我从路径中删除 Backbone: "backbone",我不会收到模块“Backbone”丢失的错误消息。 我没有在nodejs服务器上安装Backbone和Underscore。

编辑: 通过将 requirejs.config baseUrl 更改为“public/javascripts/views/test_view”修复了路径问题。 Requirejs 没有使用文件路径 (test/view.coffee) 作为 baseUrl block 。对于 requirejs ['...'], (TestView) 部分,我必须使用 test/view.coffee 文件的路径。

当我使用 mocha 运行测试时,出现以下错误:

throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: Calling node's require("../public/javascripts/views/test_view")
  failed with error: TypeError: Object #<Object> has no method 'load'

编辑: 我忘了提及我已将“jade!templates/test_template”添加到我的 test_view 中。 我把它删除了,现在 mocha 正在运行测试。但我收到错误:

TypeError: object is not a function
  at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)

行:

view = new TestView()

导致错误。

最佳答案

这里的问题是,在服务器上,RequireJS 回退到 Node 的 require()。一个可能的解决方案是使用 NPM 安装 Backbone,并将 node_modules/backbone/backbone.js 符号链接(symbolic link)到 public/lib/backbone.js。然后,您可以使用 Node 或 RequireJS 的 require() 来请求主干网。

关于node.js - 在 Node js 中使用 mocha 测试主干 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242842/

相关文章:

Node.js 内置加密货币 : RSA Decryption

node.js - 如何为 AWS Elastic Beanstalk 部署运行 npm 脚本?

javascript - RequireJS with Knockout - 多次应用绑定(bind)

javascript - Requirejs 忽略可选依赖项的加载错误

performance - 优化 Node.js 入站/出站连接

mysql - 无法使用sequelize和无服务器框架从部署的 Node azure功能连接到mysql灵活服务器

javascript - Backbone 关系事件没有触发?

javascript - 主干事件未触发

javascript - 使用 Backbone 和 Node 将模型保存到服务器

javascript - 动态更新 Ace 编辑器的语法高亮模式规则