向 NodeJS 应用程序添加单元/集成测试
我有一段连接到 MySQL 数据库的 NodeJS 代码。如何在 Jenkins Pipeline 的构建阶段之前向这段代码添加单元/集成测试(只有测试通过,构建才会开始)?
在这种情况下,测试应检查
- 与数据库的连接是否正常工作。
- SQL 查询返回正确的文本。
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');
require('dotenv').config({ debug: true })
console.log(process.env) // remove this after you've confirmed it working
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'dev-mysqldb',
user: 'mysqluser',
password: process.env.PASSWORD,
database: 'hello_world'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
//show all products
app.get('/',(req, res) => {
let sql = "SELECT * FROM messages";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
// res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
res.send(results);
});
});
//Server listening
app.listen(80,() =>{
console.log('Server started on port 80...');
});
I have this piece of NodeJS code which connects to a MySQL database. How can add unit/integration tests to this piece of code before the build stage in the Jenkins Pipeline(only if the tests pass, then the build will start)?
In this case, the tests should check that
- Connectivity to the database is working
- The correct text is returned from the SQL query.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');
require('dotenv').config({ debug: true })
console.log(process.env) // remove this after you've confirmed it working
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'dev-mysqldb',
user: 'mysqluser',
password: process.env.PASSWORD,
database: 'hello_world'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
//show all products
app.get('/',(req, res) => {
let sql = "SELECT * FROM messages";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
// res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
res.send(results);
});
});
//Server listening
app.listen(80,() =>{
console.log('Server started on port 80...');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论