[英]Unit testing app using node.js and azure functions with SQL
How can I start unit testing my application?如何开始对我的应用程序进行单元测试? First of I wanna test that I can access my SQL database.
首先我想测试我可以访问我的 SQL 数据库。 Second i wanna test how i can test the creation of a new User
其次,我想测试如何测试新用户的创建
I can't seem to find any documentation on this subject我似乎找不到有关此主题的任何文档
Which kind of test framework can i use, mocha & chai?我可以使用哪种测试框架,mocha 和 chai?
This is my azure function for register这是我的 azure function 注册
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.')
try {
await db.startDb(); //start db connection
} catch (error) {
console.log("Error connecting to the database", error.message)
}
switch (req.method) {
case 'GET':
await get(context, req);
break;
case 'POST':
await post(context, req);
break
default:
context.res = {
body: "Please get or post"
};
break
}
}
async function get(context, req){
try{
let name = req.query.name;
let user = await db.select(name)
context.res = {
body: user
};
} catch(error){
context.res = {
status: 400,
body: `No user - ${error.message}`
}
}
}
async function post(context, req){
try{
let payload = req.body;
await db.insert(payload)
console.log(payload)
context.res = {
body: ["succes"]
}
} catch(error){
context.res = {
status: 400,
body: error.message
}
}
}
This is my DB file这是我的数据库文件
const { Connection, Request, TYPES } = require('tedious');
const config = require('./config.json');
const jwt = require("jsonwebtoken");
const safeJWT = require("../middleware/Jwt")
const bcrypt = require("bcryptjs");
var connection = new Connection(config);
function startDb() {
return new Promise((resolve, reject) => {
connection.on('connect', (err) => {
if (err) {
console.log('Connection failed')
reject(err)
throw (err);
} else {
console.log('Connected')
resolve();
}
})
connection.connect();
})
}
module.exports.sqlConnection = connection
module.exports.startDb = startDb
This is some of my register.js file这是我的一些 register.js 文件
fetch("http://localhost:7071/api/register", {
method: 'POST',
body: JSON.stringify({
username: username,
email: email,
password: password
}),
headers: {
"Content-Type": "application/json; charset-UTF-8"
}
}).then((response) =>
response.json()).then((data) => {
if(data[0] = "succes"){
location.href = "login.html"
} else {
alert("failed")
}
}).catch((err) => {
console.log(err)
})
})
Well Unit tests are done in isolation and they are testing one unit.那么单元测试是独立完成的,他们正在测试一个单元。 You should not test database and etc., if you want to test user creation with the database that will be e2e test.
如果要使用将要进行 e2e 测试的数据库来测试用户创建,则不应测试数据库等。
For unit tests mock the database calls.对于单元测试模拟数据库调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.