2015-02-09 74 views
0

我正在使用grunt,mocha和chai來運行基本的單元測試。我的單元測試看起來如下node js chai mocha「ReferenceError:找不到變量require」

describe('SPSearchConnection', function() { 
describe('#performSearch()', function() { 
    it('should return zero or more results', function() { 
     var spSearchConnect = require('../index'); 
     alert(spSearchConnect); 
     chai.assert.equal(-1, [1, 2, 3].indexOf(5)); 
    }); 
}); 
}); 

現在,當我使用咕嚕「咕嚕」我收到以下錯誤運行測試:

ReferenceError: Can't find variable: require 

我gruntfile.js看起來是這樣的:

// Gruntfile.js 
module.exports = function (grunt) { 
grunt.initConfig({ 
    pkg: grunt.file.readJSON('package.json'), 

    // Mocha 
    mocha: { 
     all: { 
      src: ['tests/testrunner.html'], 
     }, 
     options: { 
      run: true 
     } 
    } 
}); 

// Load grunt mocha task 
grunt.loadNpmTasks('grunt-mocha'); 

grunt.registerTask('default', ['mocha']); 

};

我testrunner.html文件看起來像這樣:

<html> 
<head> 
<meta charset="utf-8"> 
<title>Mocha Tests</title> 
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" /> 
</head> 
<body> 
<div id="mocha"></div> 
<script src="../node_modules/mocha/mocha.js"></script> 
<script src="../node_modules/chai/chai.js"></script> 

<script> 
    mocha.setup('bdd') 
    mocha.reporter('html'); 
</script> 

<!-- Tests --> 
<script src="tests.js"></script> 

<!-- Tests --> 
<script></script> 

<script> 
    // Only tests run in real browser, injected script run if options.run == true 
    if (navigator.userAgent.indexOf('PhantomJS') < 0) { 
     mocha.run(); 
    } 
</script> 
</body> 
</html> 

有人能告訴我如何解決這個問題嗎?

回答

0

單元測試有行require('../index'),但問題是,你的測試是要在瀏覽器環境中,不具有天然require功能(因此ReferenceError)運行。如果您需要包含一個單獨的文件,您可以使用"requirejs"庫(其中用於瀏覽器)。或者您可以在HTML文件中使用<script>標籤?或者可能只是一個簡單的Ajax調用...

+2

使用「requirejs」我應該包括什麼以使require功能可用?你能給我一個工作樣本嗎? – user3547774 2015-02-10 04:16:31

相關問題