2015-04-06 27 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)插件我能夠很容易地實現我想要的東西。 –