[英]How to perform nodeJS integration tests with Jasmine?
我有一個用nodeJS編寫的服務器應用程序,可用作REST Api。 對於單元測試,我使用Jasmine,並且我還要對一些模擬數據執行一些集成測試。 像這樣測試:
從“ ../support/api-test-client”導入ApiTestClient;
import User from "../../src/model/user";
describe("GET /users", () => {
it("returns an array with all users", done => {
ApiTestClient
.getUsers()
.then(users => {
expect(users).toEqual(jasmine.any(Array));
done();
})
.catch(err => fail(err));
});
});
使用普通的單元測試,我只是可以模擬API調用,但是在這種情況下,我必須首先運行服務器應用程序,打開2個終端,一個用於npm start
,然后另一個用於npm test
。
到目前為止,我已經嘗試將此預測試腳本添加到package.json
:
"pretest": "node dist/src/server.js &"
因此,該過程在后台運行,但是感覺不正確,因為它將在測試套件結束后運行。
如何運行該集成測試以自動啟動/停止服務器應用程序?
我找到了一種簡單的方法,可以使用beforeEach
在套件之前開始express
。
注意:此文件已在jasmine 2.6.0
和express 4.15.3
上進行了測試
最小示例:
//server.js
const express = require('express')
const app = express()
app.get('/world', function (req, res) {
res.send('Hello World!')
})
app.get('/moon', function (req, res) {
res.send('Hello Moon!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
//spec/HelloSpec.js
var request = require("request");
describe("GET /world", function() {
beforeEach(function() {
//we start express app here
require("../server.js");
});
//note 'done' callback, needed as request is asynchronous
it("returns Hello World!", function(done) {
request("http://localhost:3000/world", function(error, response, html){
expect(html).toBe("Hello World!");
done();
});
});
it("returns 404", function(done) {
request("http://localhost:3000/mars", function(error, response, html){
expect(response.statusCode).toBe(404);
done();
});
});
});
使用jasmine
命令運行后,它返回預期的結果:
Started
Example app listening on port 3000!
..
2 specs, 0 failures
Finished in 0.129 seconds
並且服務器已關閉(端口3000也已關閉)
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.