Skip to content

Commit

Permalink
add second test case for endpoint /actions/all with query parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
venuswku committed Jun 4, 2022
1 parent acac509 commit 1fd6889
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 37 deletions.
18 changes: 10 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Connect server to MongoDB database.
// Connect server to MongoDB database (tests create own connection).
// uri = where Mongo database is stored (get from MongoDB dashboard)
const uri = (process.env.NODE_ENV === "prod") ? process.env.MONGODB_ATLAS_PROD_URI : process.env.MONGODB_ATLAS_TEST_URI;
mongoose.connect(uri);
// Print in terminal once MongoDB connection is open.
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Mongoose database connection established successfully.");
});
if (process.env.NODE_ENV === "prod") {
const uri = process.env.MONGODB_ATLAS_PROD_URI;
mongoose.connect(uri);
// Print in terminal once MongoDB connection is open.
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Mongoose database connection established successfully.");
});
}

// Require/import server routers.
const actionsRouter = require("./routes/actions");
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"description": "My first REST API!",
"main": "server.js",
"scripts": {
"start": "nodemon server",
"test": "jest --coverage"
"start": "SET NODE_ENV=prod&&nodemon server",
"test": "SET NODE_ENV=test&&jest --coverage --detectOpenHandles"
},
"repository": {
"type": "git",
Expand Down
18 changes: 17 additions & 1 deletion routes/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,30 @@ router.route("/suggest").post((req, res) => {
});

// Route: /actions/
// Reads and returns all actions from the MongoDB Atlas database.
// Reads and returns all APPROVED actions from the MongoDB Atlas database.
// If query parameter values with the key "for" are provided, we only return filtered actions.
router.route("/").get((req, res) => {
const forFilters = req.query.for;
if (forFilters) {
Action.find({ "for": { $in: forFilters } }) // find() returns actions that match at least one of the given `for` parameter values
.then(filteredActions => res.json(filteredActions)) // then returns actions in JSON format
.catch(err => res.status(400).json("Error getting filtered acts of kindness: " + err));
} else {
Action.find({ approved: true })
.then(actions => res.json(actions))
.catch(err => res.status(400).json("Error getting all approved acts of kindness: " + err));
}
});

// Route: /actions/all
// Reads and returns ALL actions from the MongoDB Atlas database.
// If query parameter values with the key "for" are provided, we only return filtered actions.
router.route("/all").get((req, res) => {
const forFilters = req.query.for;
if (forFilters) {
Action.find({ "for": { $in: forFilters } })
.then(filteredActions => res.json(filteredActions))
.catch(err => res.status(400).json("Error getting filtered acts of kindness: " + err));
} else {
Action.find()
.then(actions => res.json(actions))
Expand Down
10 changes: 6 additions & 4 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const app = require("./app");

// Tell server to start listening to a certain port.
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running at: http://localhost:${port}/.`);
});
if (process.env.NODE_ENV === "prod") {
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running at: http://localhost:${port}/.`);
});
}
81 changes: 59 additions & 22 deletions tests/action.test.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
// Jest documentation: https://jestjs.io/docs/using-matchers

// Require supertest and app to test HTTP requests/responses for action-related endpoints.
const app = require("../app");
const request = require("supertest");
const mongoose = require("mongoose");

// // Connect to MongoDB before all tests. -> don't need this because we already connected to database in app.js!
// beforeAll(() => {
// mongoose.connect(process.env.MONGODB_ATLAS_TEST_URI,
// { useNewUrlParser: true, useUnifiedTopology: true }
// );
// });

// Clear out all data in test database after each test case.
afterEach(() => {
const collections = mongoose.connection.collections;
for (const key in collections) {
const collection = collections[key];
collection.deleteMany();
}
// Connect to the test MongoDB before each test case.
beforeEach((done) => {
mongoose.connect(
process.env.MONGODB_ATLAS_TEST_URI,
{ useNewUrlParser: true },
() => done()
);
});

// Drop database and close the connection after each test case runs.
afterEach((done) => {
mongoose.connection.db.dropDatabase(() => {
mongoose.connection.close(() => done());
});
});

// // Disconnect and close database connection after all test cases ran.
// afterAll(async () => {
// await mongoose.connection.dropDatabase();
// await mongoose.connection.close();
// });
afterAll((done) => mongoose.connection.close(() => done()));

test("GET /actions", async () => {
test("GET /actions/all without `for` query parameter", async () => {
// Add a new document to our database so that we won't get an empty response.
const postResponse = await request(app).post("/actions/suggest").send({
"act": "Learn something new about someone",
Expand All @@ -37,14 +35,14 @@ test("GET /actions", async () => {
});

// Get/retreive the newly added action document.
await request(app).get("/actions")
await request(app).get("/actions/all")
.expect(200)
.then((response) => {
// Check type and length.
expect(Array.isArray(response.body)).toBeTruthy();
expect(response.body.length).toEqual(1);

// Check data.
// Check if required data is returned.
const postedDoc = postResponse.body.result;
const retreivedDoc = response.body[0];
expect(retreivedDoc._id).toBe(postedDoc._id);
Expand All @@ -55,4 +53,43 @@ test("GET /actions", async () => {
expect(retreivedDoc.suggestedBy).toBe(postedDoc.suggestedBy);
expect(retreivedDoc.approved).toBe(postedDoc.approved);
});
});


test("GET /actions/all with one `for` query parameter", async () => {
// Add new documents to our database so that we won't get an empty response.
const postResponse1 = await request(app).post("/actions/suggest").send({
"act": "Learn something new about someone",
"desc": "Have a nice conversation with someone around you to get to know them better.",
"for": ["stranger", "family", "friends", "yourself"],
"like": true,
"did": false,
"suggester": "6295bd3faf004a11c456da3e"
});
const postResponse2 = await request(app).post("/actions/suggest").send({
"act": "Send a handwritten letter or postcard to someone",
"desc": "Brighten a loved one's day by sharing what you appreciate about them!",
"for": ["family", "friends", "yourself"],
"like": true,
"did": true,
"suggester": "62957314cb99993a91f07ce8",
"img": "https://raw.githubusercontent.com/venuswku/cherish-api/master/images/handwritten-letter.jpg?token=GHSAT0AAAAAABUX4HZF5SDO5DK66YPFHCF6YUWUFYA"
});

// Get/retreive the newly added action document.
await request(app).get("/actions/all?for=friends")
.expect(200)
.then((response) => {
// Check type and length.
expect(Array.isArray(response.body)).toBeTruthy();
expect(response.body.length).toEqual(2);

// Check if received data contains the documents that we posted.
expect(response.body).toEqual(
expect.arrayContaining([
expect.objectContaining(postResponse1.body.result),
expect.objectContaining(postResponse2.body.result)
])
);
});
});

0 comments on commit 1fd6889

Please sign in to comment.