This is the code which I need to write the test case. I need to write a test case using jest. I wrote a test case for check the POST route of save message. but it is not working. It shows " TypeError: app.address is not a function" error message.
model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const messageSchema = new Schema(
{
user: {
type:mongoose.Schema.Types.ObjectId, required: true, ref: 'Staff'
},
writerName: { type: String, required: true },
date: { type: String, required: true },
description: { type: String, required: true },
},
{
timestamps: true,
}
);
//mongodb data table name
const Message = mongoose.model("Message", messageSchema);
module.exports = Message;
controller
const Message = require("../models/Message.Model");
const asyncHandler = require("express-async-handler");
const saveMessage = asyncHandler(async (req, res) => {
const {writerName, date, description} = req.body
const mesg = new Message({
user: req.user._id,
writerName,
date,
description
})
const createMsg = await mesg.save()
res.status(201).json(createMsg);
})
module.exports = {
saveMessage,
};
route
const express = require("express");
const router = express.Router();
const { protect } = require("../middleware/authenticationMiddleware")
const { saveMessage } = require("../controllers/message.controller");
router.route("/save").post(protect, saveMessage);
module.exports = router;
server.js
const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./config/db");
const messageRouter = require("./routes/message.routes");
const { notFound , errorHandler} = require("./middleware/errorMiddleware");
dotenv.config();
connectDB();
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("API is Running");
});
app.use("/api/message", messageRouter);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
app.listen(5000, console.log(`server is running on PORT ${PORT}`));
db.js
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(`MongoDB connected: ${conn.connection.host}`)
} catch (error) {
console.log(`Error: ${error.message}`);
process.exit();
}
};
module.exports = connectDB;
.env
MONGO_URI=
JWT_SECRET=
This is the test case which I had written
const mongoose = require("mongoose");
const request = require("supertest");
const server = require("../server");
require("dotenv").config();
/* Connecting to the database before each test. */
beforeEach(async () => {
await mongoose.connect(process.env.MONGO_URI);
});
/* Closing database connection after each test. */
afterEach(async () => {
await mongoose.connection.close();
});
describe("POST /api/message/save", () => {
it("should create a message", async () => {
const res = await request(server).post("/api/message/save").send({
user: "2",
writerName: "wN",
date: "12",
description: "Description",
});
expect(res.statusCode).toBe(201);
expect(res.body.name).toBe("Message 1");
});
});
This is the error which I had
> [email protected] test
> cross-env NODE_ENV=test jest --testTimeout=5000
console.log
server is running on PORT 5000
at Object.log (server.js:34:26)
console.log
MongoDB connected: ac-asr02at.mongodb.net
at log (config/db.js:10:17)
FAIL test/test.js
POST /api/message/save
× should create a message (1328 ms)
● POST /api/message/save › should create a message
TypeError: app.address is not a function
19 | describe("POST /api/message/save", () => {
20 | it("should create a message", async () => {
> 21 | const res = await request(server).post("/api/message/save").send({
| ^
22 | user: "2",
23 | writerName: "1009",
24 | date: "Description 2",
at Test.serverAddress (node_modules/supertest/lib/test.js:46:22)
at new Test (node_modules/supertest/lib/test.js:34:14)
at Object.obj.<computed> [as post] (node_modules/supertest/index.js:43:18)
at Object.post (test/test.js:21:39)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 3.101 s
Ran all test suites.
CodePudding user response:
You are importing your server like this:
const server = require("../server");
But you are not exporting anything from that file. You need to modify it to export your express app
module.export = app;