[英]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.