|
| 1 | +import mongoose, { model } from 'mongoose'; |
| 2 | +import { apiKeySchema } from '../apiKey'; |
| 3 | + |
| 4 | +const ApiKey = model('ApiKey', apiKeySchema); |
| 5 | + |
| 6 | +describe('ApiKey schema', () => { |
| 7 | + it('should set default label and generate an id virtual', () => { |
| 8 | + const doc = new ApiKey({ hashedKey: 'supersecret' }); |
| 9 | + |
| 10 | + expect(doc.label).toBe('API Key'); |
| 11 | + |
| 12 | + // _id is always generated |
| 13 | + expect(doc._id).toBeInstanceOf(mongoose.Types.ObjectId); |
| 14 | + |
| 15 | + // id virtual is stringified _id |
| 16 | + expect(typeof doc.id).toBe('string'); |
| 17 | + expect(doc.id).toEqual(doc._id.toHexString()); |
| 18 | + }); |
| 19 | + |
| 20 | + it('should exclude hashedKey from toObject and toJSON', () => { |
| 21 | + const doc = new ApiKey({ hashedKey: 'supersecret', label: 'Test Key' }); |
| 22 | + |
| 23 | + const obj = doc.toObject(); |
| 24 | + const json = doc.toJSON(); |
| 25 | + |
| 26 | + expect(obj).not.toHaveProperty('hashedKey'); |
| 27 | + expect(json).not.toHaveProperty('hashedKey'); |
| 28 | + }); |
| 29 | + |
| 30 | + it('should include id, label, lastUsedAt, createdAt and updatedAt in output', () => { |
| 31 | + const now = new Date(); |
| 32 | + const doc = new ApiKey({ |
| 33 | + hashedKey: 'supersecret', |
| 34 | + label: 'My Key', |
| 35 | + lastUsedAt: now |
| 36 | + }); |
| 37 | + |
| 38 | + // mock timestamps (normally set on save) |
| 39 | + doc.createdAt = new Date('2025-01-01T00:00:00Z'); |
| 40 | + doc.updatedAt = new Date('2025-01-02T00:00:00Z'); |
| 41 | + |
| 42 | + const obj = doc.toObject(); |
| 43 | + |
| 44 | + expect(obj).toMatchObject({ |
| 45 | + id: expect.any(String), |
| 46 | + label: 'My Key', |
| 47 | + lastUsedAt: now, |
| 48 | + createdAt: new Date('2025-01-01T00:00:00Z') |
| 49 | + }); |
| 50 | + }); |
| 51 | +}); |
0 commit comments