如何使用Mocha测试"正常"(非节点特定)JavaScript函数?

Mar*_*ell 48 javascript unit-testing mocha.js node.js

这似乎应该非常简单; 然而,经过两个小时的阅读和反复试验没有成功,我承认失败并问你们!

我正在尝试使用MochaShould.js来测试一些JavaScript函数,但我遇到了范围问题.我已将其简化为最基本的测试用例,但我无法使其正常工作.

我有一个名为的文件functions.js,它只包含以下内容:

function testFunction() {
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

而我tests.js(位于同一文件夹中)的内容:

require('./functions.js')

describe('tests', function(){
    describe('testFunction', function(){
        it('should return 1', function(){
            testFunction().should.equal(1);
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

这个测试失败了ReferenceError: testFunction is not defined.

我可以看到原因,因为我发现的大多数示例都是将对象和函数附加到Node global对象或使用module.exports-but 导出它们但是使用这些方法中的任何一种意味着我的函数代码会在标准浏览器情况下抛出错误,其中那些对象不存在

那么如何在不使用特定于Node的语法的情况下访问在我的测试的单独脚本文件中声明的独立函数?

Mar*_*ell 27

感谢这里的其他答案,我已经有了工作.

有一件事虽未提及 - 也许是因为它在Noders中的常识 - 是你需要将require调用的结果分配给变量,这样你就可以在测试套件中调用导出的函数时引用它.

这是我的完整代码,供将来参考:

functions.js:

function testFunction () {
    return 1;
}

// If we're running under Node, 
if(typeof exports !== 'undefined') {
    exports.testFunction = testFunction;
}
Run Code Online (Sandbox Code Playgroud)

tests.js:

var myCode = require('./functions')

describe('tests', function(){
    describe('testFunction', function(){
        it('should return 1', function(){
            // Call the exported function from the module
            myCode.testFunction().should.equal(1);
        })
    })
})
Run Code Online (Sandbox Code Playgroud)


Ric*_*asi 19

require('./functions.js')
Run Code Online (Sandbox Code Playgroud)

由于您没有输出任何内容,因此无法执行任何操作.你期待的testFunction是全球可用的,基本上是相同的

global.testFunction = function() {
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

无法绕过export/globals机制.这是节点设计的方式.没有隐式的全局共享上下文(如window在浏览器上).模块中的每个"全局"变量都被困在其上下文中.

你应该用module.exports.如果您打算与浏览器环境共享该文件,可以使其兼容.对于快速入侵,只需window.module = {}; jQuery.extend(window, module.exports)在浏览器或if (typeof exports !== 'undefined'){ exports.testFunction = testFunction }节点中进行即可.

  • 好的,这很有意义,谢谢.那么Mocha不是真的打算用于测试非Node JS吗?它没有提到我遇到过的任何文档或教程中的任何地方. (6认同)

dri*_*hev 7

如果您想要通过要求使用任何模块,您应该使用

module.exports
Run Code Online (Sandbox Code Playgroud)

如你所知 ;)

如果你想通过这样做在Node和浏览器中使用模块,有一个解决方案

function testFunction() { /* code */ }

if (typeof exports !== 'undefined') {
   exports.testFunction = testFunction
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,您将能够在浏览器和节点环境中使用该文件