When building a CRUD application using Node.js and MongoDB, ensuring the functionality of your application through effective testing is crucial. This guide covers how to test CRUD operations using TypeScript with a focus on clarity and simplicity. By the end, you will understand how to set up your testing environment, write test cases, and run them effectively.
Before diving into testing CRUD operations, we need to set up a suitable environment. For this, we can use Jest as our testing framework and supertest to test our API endpoints. Here’s how to do it:
Install Required Packages:
First, make sure you have installed Jest and supertest in your Node.js application. You can do this by running:
npm install --save-dev jest supertest @types/jest
Create a Testing Directory:
It’s a good practice to keep your tests organized. Create a __tests__
directory in your project root where you will place your test files.
Configure Jest:
In your package.json
, add the following script to run tests:
"scripts": { "test": "jest" }
Create Your API File:
Let's assume you have a basic Express API setup like below:
import express from 'express'; import mongoose from 'mongoose'; const app = express(); app.use(express.json()); const Item = mongoose.model('Item', new mongoose.Schema({ name: String, })); app.post('/items', async (req, res) => { const item = new Item(req.body); await item.save(); return res.status(201).send(item); }); app.get('/items', async (req, res) => { const items = await Item.find(); return res.status(200).send(items); }); app.put('/items/:id', async (req, res) => { const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); return res.send(item); }); app.delete('/items/:id', async (req, res) => { await Item.findByIdAndDelete(req.params.id); return res.sendStatus(204); }); export default app;
Now, let’s write tests for our CRUD operations. Create a file named item.test.ts
in your __tests__
directory.
Here's how you can write tests for each CRUD operation:
import request from 'supertest'; import app from '../path/to/your/app'; import mongoose from 'mongoose'; beforeAll(async () => { // Connect to in-memory MongoDB instance here await mongoose.connect(/* MongoDB URI */, { useNewUrlParser: true, useUnifiedTopology: true }); }); afterAll(async () => { // Clean up and close DB connection await mongoose.connection.close(); }); describe('POST /items', () => { it('should create a new item', async () => { const response = await request(app) .post('/items') .send({ name: 'Test Item' }) .expect(201); expect(response.body).toHaveProperty('_id'); expect(response.body.name).toBe('Test Item'); }); });
describe('GET /items', () => { it('should fetch all items', async () => { const response = await request(app).get('/items').expect(200); expect(Array.isArray(response.body)).toBeTruthy(); }); });
describe('PUT /items/:id', () => { it('should update an existing item', async () => { const itemResponse = await request(app) .post('/items') .send({ name: 'Old Item' }); const updateResponse = await request(app) .put(`/items/${itemResponse.body._id}`) .send({ name: 'Updated Item' }) .expect(200); expect(updateResponse.body.name).toBe('Updated Item'); }); });
describe('DELETE /items/:id', () => { it('should delete an item', async () => { const itemResponse = await request(app) .post('/items') .send({ name: 'Item to Delete' }); await request(app).delete(`/items/${itemResponse.body._id}`).expect(204); const fetchResponse = await request(app).get('/items'); expect(fetchResponse.body).toHaveLength(0); }); });
To execute the tests, run the following command in your terminal:
npm test
You should see output indicating that all your tests have passed. If any test fails, the console will provide you with helpful information to track down the issue.
Testing CRUD operations in your Node.js application is a crucial part of the development process. By incorporating tests with Jest and supertest, you not only ensure your application behaves as expected, but also make it easier to refactor and maintain in the long run.
Now that you have set up and written tests for your CRUD operations, continue to explore more advanced testing techniques and practices, such as integration tests and mocking utilities. Happy coding!
14/10/2024 | NodeJS
08/10/2024 | NodeJS
31/08/2024 | NodeJS
23/07/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
18/09/2024 | NodeJS
23/07/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS