Skip to content

Commit b121e87

Browse files
committed
test: add edge case coverage for User model
1 parent 8d17610 commit b121e87

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

spec/user.model.spec.cjs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,84 @@ describe('User Model', () => {
4444
const isNotMatch = await user.comparePassword('wrongpassword');
4545
expect(isNotMatch).toBeFalse();
4646
});
47+
48+
it('should hash password again when password is modified', async () => {
49+
const user = new User({
50+
username: 'testuser4',
51+
email: 'test4@example.com',
52+
password: 'password123',
53+
});
54+
55+
await user.save();
56+
57+
const oldHash = user.password;
58+
59+
user.password = 'newpassword123';
60+
await user.save();
61+
62+
expect(user.password).not.toBe(oldHash);
63+
64+
const isMatch = await bcrypt.compare('newpassword123', user.password);
65+
expect(isMatch).toBeTrue();
66+
});
67+
68+
it('should reject user without email', async () => {
69+
const user = new User({
70+
username: 'testuser5',
71+
password: 'password123',
72+
});
73+
74+
await expectAsync(user.save()).toBeRejected();
75+
});
76+
77+
it('should reject user without username', async () => {
78+
const user = new User({
79+
email: 'test5@example.com',
80+
password: 'password123',
81+
});
82+
83+
await expectAsync(user.save()).toBeRejected();
84+
});
85+
86+
it('should reject user without password', async () => {
87+
const user = new User({
88+
username: 'testuser6',
89+
email: 'test6@example.com',
90+
});
91+
92+
await expectAsync(user.save()).toBeRejected();
93+
});
94+
95+
it('should fail password comparison for empty password', async () => {
96+
const user = new User({
97+
username: 'testuser7',
98+
email: 'test7@example.com',
99+
password: 'password123',
100+
});
101+
102+
await user.save();
103+
104+
const isMatch = await user.comparePassword('');
105+
expect(isMatch).toBeFalse();
106+
});
107+
108+
it('should generate different hashes for same password', async () => {
109+
const user1 = new User({
110+
username: 'user1',
111+
email: 'user1@example.com',
112+
password: 'samepassword',
113+
});
114+
115+
const user2 = new User({
116+
username: 'user2',
117+
email: 'user2@example.com',
118+
password: 'samepassword',
119+
});
120+
121+
await user1.save();
122+
await user2.save();
123+
124+
expect(user1.password).not.toBe(user2.password);
125+
});
126+
47127
});

0 commit comments

Comments
 (0)