Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / docs-core / lib / UseCase / EncryptMessage.spec.ts
blob656f9ab16d12855727f63b4e387c8a3f04edd605
1 import { Result } from '@proton/docs-shared'
2 import type { EncryptionService } from '../Services/Encryption/EncryptionService'
3 import type { EncryptionContext } from '../Services/Encryption/EncryptionContext'
4 import type { DocumentKeys } from '@proton/drive-store'
5 import { EncryptMessage } from './EncryptMessage'
6 import { GetAssociatedEncryptionDataForRealtimeMessage } from './GetAdditionalEncryptionData'
8 jest.mock('../Services/Encryption/EncryptionService')
9 jest.mock('./GetAdditionalEncryptionData')
11 describe('EncryptMessage', () => {
12   let encryptMessage: EncryptMessage
13   let encryptionService: jest.Mocked<EncryptionService<EncryptionContext.RealtimeMessage>>
15   const update = new Uint8Array()
16   const metadata = { version: 1, authorAddress: 'author@example.com', timestamp: 1234567890 }
17   const keys = {
18     userAddressPrivateKey: {},
19     documentContentKey: {},
20     userOwnAddress: 'user@example.com',
21   } as unknown as DocumentKeys
23   beforeEach(() => {
24     encryptionService = {
25       signAndEncryptData: jest.fn().mockResolvedValue(Result.ok(new Uint8Array())),
26       decryptData: jest.fn().mockResolvedValue(Result.ok(new Uint8Array())),
27     } as unknown as jest.Mocked<EncryptionService<EncryptionContext.RealtimeMessage>>
29     encryptMessage = new EncryptMessage(encryptionService)
30   })
32   it('should call signAndEncryptData with correct parameters', async () => {
33     const associatedData = new Uint8Array([1, 2, 3])
34     ;(GetAssociatedEncryptionDataForRealtimeMessage as jest.Mock).mockReturnValue(associatedData)
35     encryptionService.signAndEncryptData.mockResolvedValue(Result.ok(new Uint8Array([4, 5, 6])))
37     await encryptMessage.execute(update, metadata, keys)
39     expect(GetAssociatedEncryptionDataForRealtimeMessage).toHaveBeenCalledWith(metadata)
40     expect(encryptionService.signAndEncryptData).toHaveBeenCalledWith(
41       update,
42       associatedData,
43       keys.documentContentKey,
44       keys.userAddressPrivateKey,
45     )
46   })
48   it('should return encrypted data on success', async () => {
49     const encryptedData = new Uint8Array([4, 5, 6])
50     encryptionService.signAndEncryptData = jest.fn().mockResolvedValue(Result.ok(encryptedData))
52     const result = await encryptMessage.execute(update, metadata, keys)
54     expect(result.isFailed()).toBe(false)
55     expect(result.getValue()).toEqual(encryptedData)
56   })
58   it('should fail if signAndEncryptData fails', async () => {
59     encryptionService.signAndEncryptData.mockResolvedValue(Result.fail('error'))
61     const result = await encryptMessage.execute(update, metadata, keys)
63     expect(result.isFailed()).toBe(true)
64     expect(result.getError()).toBe('error')
65   })