当我使用 nodemon 运行这段代码时运行良好
import express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import nodemailer from 'nodemailer';
import { config } from 'dotenv';
import User = require('../schemas/users');
import Otp = require('../schemas/otp');
const router = express.Router();
config();
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
router.post('/login', async (req: express.Request, res: express.Response) => {
const { username, password } = req.body;
if (!username || !password) {
res.status(409).json({ status: 'INVALID_REQUEST' });
return;
}
const search = await User.find({ username });
if (search.length !== 1) {
res.status(409).json({ status: 'NO_SUCH_USER' });
return;
}
if (!(await bcrypt.compare(password, search[0].password!))) {
res.status(409).json({ status: 'INVALID_PASSWORD' });
return;
}
const accessToken = jwt.sign({ username }, process.env.ACCESS_TOKEN_SECRET!);
res.status(200).json({ status: "SUCCESS", accessToken: accessToken });
});
router.post(
'/register',
async (req: express.Request, res: express.Response) => {
const { username, email, password } = req.body;
if (!username || !password) {
res.status(409).json({ status: 'INVALID_REQUEST' });
return;
}
const hashedPassword = await bcrypt.hash(password, 10);
try {
const user = new User({ username:username, password:hashedPassword });
await user.save();
if (!email) {
res.status(200).json({ status: 'SUCCESS' });
return;
}
const expiresat = Date.now() + 3600000;
const otpnumber = `${Math.floor(1000 + Math.random() * 9000)}`;
const otp = new Otp({ username, otpnumber, expiresat, email });
await otp.save();
const mailOptions = {
from: '[email protected]',
to: email,
subject: 'verify your email',
html: `<p>Enter <b>${otpnumber}</b></p>`,
};
await transporter.sendMail(mailOptions);
res.status(200).json({ status: 'SUCCESS_MAIL_SENT' });
} catch (err: any) {
if (err.code === 11000) {
res.status(409).json({ status: 'USERNAME_ALREADY_EXISTS' });
} else {
res.status(500).json({ status: 'UNKNOWN_ERROR' });
}
}
},
);
router.post(
'/verifyotp',
async (req: express.Request, res: express.Response) => {
const { username, enteredotp } = req.body;
const search = await Otp.find({ username });
if (search.length === 0) {
res.status(409).json({ status: 'ALREADY_VERIFIED' });
return;
}
const { otpnumber, expiresat, email } = search[0];
if (expiresat!.getTime() < Date.now()) {
await Otp.deleteMany({ username });
res.status(409).json({ status: 'CODE_EXPIRED' });
return;
}
if (otpnumber !== enteredotp) {
res.status(409).json({ status: 'INVALID_CODE' });
return;
}
await Otp.deleteMany({ username });
await User.updateOne({ username }, { $set: { email } });
res.status(200).json({ status: 'SUCCESS' });
},
);
export = router;
但是当我运行我的测试用例时是这样的:
import request from 'supertest';
import app from '../app';
import db from '../DBconnection';
beforeAll(async()=>{
await db.ConnectDb('testQueryExchange');
});
afterAll(async()=>{
await db.disconnectDB();
}
)
describe('Test the Register API', () => {
it('It should respond with 409 for not giving username or password', async () => {
const response = await request(app).post('/auth/register');
expect(response.statusCode).toBe(409);
expect(response.body.status).toBe('INVALID_REQUEST');
});
it('It should respond with SUCCESS MESSAGE when no email given', async () => {
const response = await request(app).post('/auth/register').send({username: 'Nithin',password: 'happynithin123'});
expect(response.statusCode).toBe(200);
expect(response.body.status).toBe('SUCCESS');
});
it('It should respond with SUCCESS_MAIL_SENT MESSAGE when email given', async () => {
const response = await request(app).post('/auth/register').send({username: 'Nissi',email:'happynithin123',password: 'happynissi123'});
expect(response.body.status).toBe('SUCCESS_MAIL_SENT');
});
it('It should respond with USERNAME_ALREADY_EXISTS MESSAGE when existing user registers', async () => {
const response = await request(app).post('/auth/register').send({username: 'Nissi',email:'happynithin123',password: 'happynissi123'});
expect(response.statusCode).toBe(409);
expect(response.body.status).toBe('USERNAME_ALREADY_EXISTS');
});
describe('Test the Login API', () => {
it('It should respond with 200 with accesstoken', async () => {
const response = await request(app).post('/auth/login').send({username: 'Nithin',password: 'happynithin123'});;
expect(response.statusCode).toBe(200);
expect(response.body.status).toBe('SUCCESS');
});});
});
此测试用例失败“它应该在给定电子邮件时以 SUCCESS_MAIL_SENT MESSAGE 响应” 因为 /register api 中的 catch 语句抛出 "{"code": "EENVELOPE", "command": "API"}"
我试图在我的代码上运行测试用例,但是第三个测试用例一直失败,即使它在我运行 nodemon 并在 postman 中测试 api 时仍然有效