From bbe51ac3c172efeb503d693fe517e662e3550647 Mon Sep 17 00:00:00 2001 From: luoyonghuang <2308014474@qq.com> Date: Thu, 10 Oct 2024 21:12:46 +0800 Subject: [PATCH] new file: test/score.test.js new file: test/server.test.js --- test/score.test.js | 49 +++++++++++++++++++++++++++++++++++++++++++++ test/server.test.js | 18 +++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 test/score.test.js create mode 100644 test/server.test.js diff --git a/test/score.test.js b/test/score.test.js new file mode 100644 index 0000000..4faa0e7 --- /dev/null +++ b/test/score.test.js @@ -0,0 +1,49 @@ +const chai = require('chai'); +const chaiHttp = require('chai-http'); +const app = require('../server'); // 引入 Express 应用 +const pool = require('../db'); // 引入数据库连接池 +const expect = chai.expect; + +chai.use(chaiHttp); + +describe('Student Score API Tests', () => { + // 在测试开始前准备一些测试数据 + before(async () => { + const connection = await pool.getConnection(); + await connection.query('INSERT INTO students (student_id, student_name, score, call_count) VALUES (123456, "HE", 85, 0)'); + await connection.query('INSERT INTO students (student_id, student_name, score, call_count) VALUES (412536, "dfe", 90, 0)'); + connection.release(); + }); + + // 测试结束后清理数据 + after(async () => { + const connection = await pool.getConnection(); + await connection.query('DELETE FROM students WHERE student_id IN (123456, 412536)'); + connection.release(); + }); + + it('should return score of an existing student', (done) => { + chai.request(app) + .post('/api/get-score') + .send({ student_id: 123456 }) + .end((err, res) => { + expect(res).to.have.status(200); + expect(res.body).to.be.an('object'); + expect(res.body).to.have.property('student_id', 123456); + expect(Number(res.body.score)).to.equal(85); // 将 score 转为数值进行比较 + done(); + }); + }); + + it('should return 404 for a non-existing student', (done) => { + chai.request(app) + .post('/api/get-score') + .send({ student_id: 999 }) // 使用不存在的 ID + .end((err, res) => { + expect(res).to.have.status(404); + expect(res.body).to.be.an('object'); + expect(res.body).to.have.property('message', '学生不存在'); + done(); + }); + }); +}); diff --git a/test/server.test.js b/test/server.test.js new file mode 100644 index 0000000..fe7e5ac --- /dev/null +++ b/test/server.test.js @@ -0,0 +1,18 @@ +const chai = require('chai'); +const chaiHttp = require('chai-http'); +const app = require('../server'); + +chai.use(chaiHttp); +const { expect } = chai; + +describe('Express Server Tests', () => { + it('should respond with status 200 on the root path', (done) => { + chai.request(app) + .get('/') + .end((err, res) => { + expect(res).to.have.status(200); + done(); + }); + }); + +});