2015-04-06 93 views
1

我想为我正在构建的项目设置测试。在我能找到的例子中,他们都说包括要测试的相关代码是通过一个require语句完成的:require('foo');。但是,我的项目不是在模块中构建的,而是在ES6类中,然后转换为ES5原型。如何在Mocha/Chai中测试JS原型(非模块)?

我想知道如何包含文件?

因此,例如,在ES6类:

class Foo { 
    constructor() { 
    // do things 
    } 
} 

大致翻译为:

// ES5 compatible code is here (_classCallCheck etc). 
var Foo = (function() {  
    function Foo() { 
    _classCallCheck(this, Foo); 

    // do things 
    } 
} 

而且我想知道如何将它包含在我的测试文件:

var expect = require('chai').expect; 
// how to require or whatever else here? 

describe('Foo', function() { 
    it('creates an Foo object', function() { 
    var foo = new Foo({}); 
    }); 
}); 

回答

2

如果你不使用模块,你可以像这样为你的测试创建一个简单的html页面:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>your tests</title> 
    <link rel="stylesheet" media="all" href="vendor/mocha.css"> 
</head> 
<body> 
    <div id="mocha"><p><a href=".">Index</a></p></div> 
    <div id="messages"></div> 
    <div id="fixtures"></div> 
    <script src="vendor/mocha.js"></script> 
    <script src="vendor/chai.js"></script> 
    <script src="your_files.js"></script> 
    <script src="your_files_test.js"></script> 
    <script>mocha.run();</script> 
</body> 
</html> 

有了这个,你不需要在你的测试文件中需要一些东西。

如果您想了解更多信息:article

我希望它会帮助你。

+0

谢谢,你送我正确的方向。我也使用Grunt,所以[本文](http://code.tutsplus.com/tutorials/testing-javascript-with-phantomjs--net-28243)以及[grunt-mocha-phantomjs]( https://github.com/jdcataldo/grunt-mocha-phantomjs)插件我能够很容易地实现我想要的东西。 –