mocha无法创建我的函数实例

时间:2014-05-15 18:36:49

标签: javascript node.js mocha

刚开始使用mocha并且不能为我的生活找出为什么它认为Helper未定义在下面的指示行/列:

test.js

var assert = require('assert'),
    helper = require('../src/js/helper.js');
describe('helper', function() {
    describe('#parseValue', function() {
        it('should return number of minutes for a properly formatted string', function() {
            assert.equal(1501, (new Helper()).parseValue('1d 1h 1m', 'when'));
                                ^^^^^^^^^^^^
        });
    });
});

helper.js

(function(exports) {

    'use strict';

    function Helper(opts) {

        this.opts = opts || {};

        /**
         *  Parse a value based on its type and return a sortable version of the original value
         *
         *  @param      {string}    val     input value
         *  @param      {string}    type    type of input value
         *  @returns    {mixed}     sortable value corresponding to the input value
         */
        this.parseValue = function(val, type) {

            switch (type) {

                case 'when':
                    var d = val.match(/\d+(?=d)/),
                        h = val.match(/\d+(?=h)/),
                        m = val.match(/\d+(?=m)/);
                    if (m)
                        m = parseInt(m, 10);
                    if (h)
                        m += parseInt(h, 10) * 60;
                    if (d)
                        m += parseInt(d, 10) * 1440;
                    val = m;
                    break;

                default:
                    break;

            }

            return val;

        };

    }

    exports.helper = Helper;

})(this);

我在没有mocha的情况下在浏览器中编写了一个快速测试,以确保我的 helper.js 功能可以访问并且工作正常,所以我真的很茫然。我通过从我的目录中的命令行调用mocha直接在我的服务器上运行它。

1 个答案:

答案 0 :(得分:1)

您永远不会在Helper中定义test.js - 此行中只有helper

var helper = require('../src/js/helper.js');

使用您定义的小写helper


顺便说一句,您可能希望从helper.js更改出口行:

exports.helper = Helper;

对此:

exports.Helper = Helper;

然后在test.js中使用帮助器,如下所示:

assert.equal(1501, (new helper.Helper()).parseValue('1d 1h 1m', 'when'));

或者只做这样的事情:

var Helper = require('../src/js/helper.js').Helper;