Open benoit-bremaud opened 1 week ago
git checkout main
git pull origin main
git checkout -b feature/unit-tests-user-model
cd backend
npm install --save-dev jest supertest
touch jest.config.js
export default {
testEnvironment: 'node',
verbose: true,
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
"scripts": {
"test:backend": "jest --config jest.config.mjs",
"test": "ng test" // Existing Angular test script
}
- [x] Make sure that your package.json uses the new configuration file:
"scripts": { "test:backend": "jest --config jest.config.mjs", "test": "ng test" // Existing Angular test script }
The package.json file that needs to be updated with the Jest configuration is the one in your backend folder, because Jest is being used to test your backend code.
Here's how you can update the package.json file in the backend folder:
Update backend/package.json Navigate to your backend directory. Open the package.json file in a text editor. Add the test script for Jest. Example backend/package.json
{
"name": "backend",
"version": "1.0.0",
"description": "Backend for the Angular Social Network project",
"main": "app.js",
"scripts": {
"start": "node app.js",
"test:backend": "jest --config jest.config.mjs"
},
"dependencies": {
"bcrypt": "^5.0.1",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.0.12"
},
"devDependencies": {
"jest": "^27.0.6",
"ts-jest": "^27.0.5",
"@types/jest": "^27.0.1",
"supertest": "^6.1.6"
}
}
This configuration adds a test:backend script that you can run to execute your Jest tests.
mkdir tests
touch tests/user.test.ts
import mongoose from 'mongoose';
import User from '../src/models/User'; // Adjust the path as necessary
import bcrypt from 'bcrypt';
describe('User Model Test', () => {
// Before running any tests, connect to the MongoDB database
beforeAll(async () => {
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
});
// After all tests are finished, close the connection
afterAll(async () => {
await mongoose.connection.close();
});
it('create & save user successfully', async () => {
const userData = {
username: 'testuser',
email: 'testuser@example.com',
password: 'password123',
};
const validUser = new User(userData);
const savedUser = await validUser.save();
// Object Id should be defined when successfully saved to MongoDB.
expect(savedUser._id).toBeDefined();
expect(savedUser.username).toBe(userData.username);
expect(savedUser.email).toBe(userData.email);
// The password should be hashed
const isPasswordHashed = await bcrypt.compare(userData.password, savedUser.password);
expect(isPasswordHashed).toBe(true);
});
it('insert user successfully, but the field does not defined in schema should be undefined', async () => {
const userWithInvalidField = new User({ username: 'testuser', email: 'testuser@example.com', password: 'password123', nickname: 'testnickname' });
const savedUserWithInvalidField = await userWithInvalidField.save();
expect(savedUserWithInvalidField._id).toBeDefined();
expect(savedUserWithInvalidField.nickName).toBeUndefined();
});
it('create user without required field should fail', async () => {
const userWithoutRequiredField = new User({ username: 'testuser' });
let err;
try {
const savedUserWithoutRequiredField = await userWithoutRequiredField.save();
err = savedUserWithoutRequiredField;
} catch (error) {
err = error;
}
expect(err).toBeInstanceOf(mongoose.Error.ValidationError);
expect(err.errors.email).toBeDefined();
});
});
Description : Write unit tests to ensure the User model behaves as expected.
Steps :