I'm trying to get better at writing tests for my Node.js APIs. My latest project has me querying an endpoint /api/v1/restaurants
that returns data including an array of objects. This is the functioning call within the controller:
restaurantRouter.get("/api/v1/restaurants", async (req, res) => {
try {
// const results = await db.query("SELECT * FROM restaurants");
const results = await select("restaurants");
res.status(200).json({
status: "success",
results: results.rows.length,
data: {
restaurants: results.rows
}
})
} catch (err) {
console.log(err)
}
})
- As you can see, I've abstracted the DB queries to a separate utility page, but I still pass the table name "restaurants" as an argument.
- Both
restaurants
and test_restaurants
tables are created and running on my local drive in the same Database.
My problem comes when I try to make API calls in my tests like so:
test("restaurants are returned as JSON", async () => {
await api
.get("/api/v1/restaurants")
.expect(200)
.expect('Content-Type', /application/json/)
})
test("all restaurants are returned", async () => {
const response = await api.get("/api/v1/restaurants")
expect(response.body.data).not.toBeEmpty()
expect(response.body.data.restaurants).toBeArrayOfSize(2)
})
They immediately default to the Dev database table restaurants
. My immediate thought was to just do the easy/lazy thing and create an identical route for tests like this:
restaurantRouter.get("/api/v1/test-restaurants", async (req, res) => {
try {
const results = await select("test_restaurants");
res.status(200).json({
status: "success",
results: results.rows.length,
data: {
restaurants: results.rows
}
})
} catch (err) {
console.log(err)
}
})
Is there a better, or more elegant way to go about testing these? Maybe using a middleware to pass in an optional variable that defaults to Dev/Prod database if no variable parameter is given?
I've been searching over the course of a couple of days and all the tutorials and examples have people using mongoDB, which seems to be easier to set up and tear down testing databases. Thanks, and let me know if more info is needed.
question from:
https://stackoverflow.com/questions/65895864/better-testing-express-routes-with-test-db-in-postgresql 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…