@@ -12,10 +12,7 @@ import { ExchangeApiKeysService } from './exchange-api-keys.service';
1212import { UserEntity , UserNotFoundError , UserRepository } from '@/modules/user' ;
1313
1414import { ExchangeApiKeyEntity } from './exchange-api-key.entity' ;
15- import {
16- ActiveExchangeApiKeyExistsError ,
17- KeyAuthorizationError ,
18- } from './exchange-api-keys.errors' ;
15+ import { KeyAuthorizationError } from './exchange-api-keys.errors' ;
1916import { ExchangeApiKeysRepository } from './exchange-api-keys.repository' ;
2017import {
2118 generateExchangeApiKey ,
@@ -104,20 +101,31 @@ describe('ExchangeApiKeysService', () => {
104101 expect ( thrownError . exchangeName ) . toBe ( input . exchangeName ) ;
105102 } ) ;
106103
107- it ( 'should throw if user already has active keys ' , async ( ) => {
104+ it ( 'should overwrite existing keys if user already has active ones ' , async ( ) => {
108105 const input = generateExchangeApiKeysData ( ) ;
106+ const existingKey = generateExchangeApiKey ( ) ;
109107 mockExchangeApiKeysRepository . findOneByUserId . mockResolvedValueOnce (
110- generateExchangeApiKey ( ) ,
108+ existingKey ,
109+ ) ;
110+ mockExchangeClient . checkRequiredAccess . mockResolvedValueOnce ( true ) ;
111+ mockUserRepository . findOneById . mockResolvedValueOnce ( {
112+ id : input . userId ,
113+ } as UserEntity ) ;
114+ mockExchangeApiKeysRepository . updateOne . mockImplementation (
115+ async ( entity ) => entity ,
111116 ) ;
112117
113- let thrownError ;
114- try {
115- await exchangeApiKeysService . enroll ( input ) ;
116- } catch ( error ) {
117- thrownError = error ;
118- }
118+ const updatedEntity = await exchangeApiKeysService . enroll ( input ) ;
119119
120- expect ( thrownError ) . toBeInstanceOf ( ActiveExchangeApiKeyExistsError ) ;
120+ expect ( mockExchangeApiKeysRepository . updateOne ) . toHaveBeenCalledWith (
121+ existingKey ,
122+ ) ;
123+ const [ decryptedApiKey , decryptedSecretKey ] = await Promise . all ( [
124+ aesEncryptionService . decrypt ( updatedEntity . apiKey ) ,
125+ aesEncryptionService . decrypt ( updatedEntity . secretKey ) ,
126+ ] ) ;
127+ expect ( decryptedApiKey . toString ( ) ) . toBe ( input . apiKey ) ;
128+ expect ( decryptedSecretKey . toString ( ) ) . toBe ( input . secretKey ) ;
121129 } ) ;
122130
123131 it ( 'should throw if user not exists' , async ( ) => {
0 commit comments