[英]How to run mocha and mocha-phantomjs tests from one “npm test” command in node.js?
[英]How to run mocha tests and node in a single npm test command ? (CI)
我想使用Circle CI來集成一個git項目。
我正在使用mocha
進行測試。
運行npm test
我想:
如何運行單個npm test
命令來運行已包含在單個index.js
文件中的節點和我的mocha測試。
我在package.json
試過這個:
"scripts": {
"test": "node server/app.js & mocha server/tests/index.js",
"start": "node server/app.js",
"postinstall": "bower install"
}
是否有一種標准的方法來運行服務器和單個命令的測試,但我錯過了什么?
我認為關鍵是在測試中運行節點服務器,而不是嘗試在另一個進程中初始化它。
您的mocha測試應該從您的應用程序的需求開始,然后您的每個測試都可以與它進行交互。
例如:
var http = require('http');
var server = http.createServer(function(req, res){
res.end('Hello World\n');
})
server.listen(8888);
describe('http', function(){
it('should provide an example', function(done){
http.get({ path: '/', port: 8888 }, function(res){
expect(res).to.have.property('statusCode', 200);
done();
})
})
})
如果在你的情況下可行,我建議使用像supertest這樣的東西來進行測試。 這樣,您可以避免在開始測試之前啟動服務器。
我知道有些情況下使用supertest
是不可能的。 在這種情況下,您可以在所有測試之前使用before
鈎子輪詢服務器,以等待它准備好:
before(function (done) {
// Set a reasonable timeout for this hook.
this.timeout(5000);
function check() {
if (serverIsReady()) {
done();
return;
}
// The server is no ready, check again in 1/10th of a second.
setTimeout(check, 100);
}
check(); // Start checking.
});
我不確定在你的情況下究竟是什么serverIsReady
。 這可能是在從Google的服務器一樣發出一個簡單的路徑,企圖GET
上的路徑/
。
我在運行需要某些先決條件的測試時所做的是使用mochas beforeEach()功能。
從文檔中
您也可以選擇任何文件並添加“root”級別掛鈎。 例如,在所有describe()塊之外添加beforeEach()。 這將導致beforeSach()的回調在任何測試用例之前運行,無論它存在於哪個文件中(這是因為Mocha有一個隱含的describe()塊,稱為“root suite”)。
beforeEach(function() {
console.log('before every test in every file');
});
在每個代碼塊之前,您可以運行命令以使用例如來自npm的exec庫來啟動服務器
https://www.npmjs.com/package/exec
這將確保您的服務器在運行測試之前運行,從而允許您只運行npm test。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.