refactor(core): Encapsulate logic to create new credential into its own method (#12361)

This commit is contained in:
Ricardo Espinoza
2024-12-27 08:26:36 -05:00
committed by GitHub
parent 6891cefa6d
commit 66f8c9e249
6 changed files with 258 additions and 15 deletions

View File

@@ -1,10 +1,16 @@
import { mock } from 'jest-mock-extended';
import { nanoId, date } from 'minifaker';
import { CREDENTIAL_EMPTY_VALUE, type ICredentialType } from 'n8n-workflow';
import { CREDENTIAL_BLANKING_VALUE } from '@/constants';
import type { CredentialTypes } from '@/credential-types';
import { CredentialsService } from '@/credentials/credentials.service';
import type { CredentialsEntity } from '@/databases/entities/credentials-entity';
import type { AuthenticatedRequest } from '@/requests';
import { createNewCredentialsPayload, credentialScopes } from './credentials.test-data';
let req = { user: { id: '123' } } as AuthenticatedRequest;
describe('CredentialsService', () => {
const credType = mock<ICredentialType>({
@@ -68,4 +74,67 @@ describe('CredentialsService', () => {
});
});
});
describe('createCredential', () => {
it('it should create new credentials and return with scopes', async () => {
// Arrange
const encryptedData = 'encryptedData';
const newCredentialPayloadData = createNewCredentialsPayload();
const newCredential = mock<CredentialsEntity>({
name: newCredentialPayloadData.name,
data: JSON.stringify(newCredentialPayloadData.data),
type: newCredentialPayloadData.type,
});
const encryptedDataResponse = {
name: newCredentialPayloadData.name,
type: newCredentialPayloadData.type,
updatedAt: date(),
data: encryptedData,
};
const saveCredentialsResponse = {
id: nanoId.nanoid(),
name: newCredentialPayloadData.name,
type: newCredentialPayloadData.type,
updatedAt: encryptedDataResponse.updatedAt,
createdAt: date(),
data: encryptedDataResponse.data,
isManaged: false,
shared: undefined,
};
service.prepareCreateData = jest.fn().mockReturnValue(newCredential);
service.createEncryptedData = jest.fn().mockImplementation(() => encryptedDataResponse);
service.save = jest.fn().mockResolvedValue(saveCredentialsResponse);
service.getCredentialScopes = jest.fn().mockReturnValue(credentialScopes);
// Act
const createdCredential = await service.createCredential(newCredentialPayloadData, req.user);
// Assert
expect(service.prepareCreateData).toHaveBeenCalledWith(newCredentialPayloadData);
expect(service.createEncryptedData).toHaveBeenCalledWith(null, newCredential);
expect(service.save).toHaveBeenCalledWith(
newCredential,
encryptedDataResponse,
req.user,
newCredentialPayloadData.projectId,
);
expect(service.getCredentialScopes).toHaveBeenCalledWith(
req.user,
saveCredentialsResponse.id,
);
expect(createdCredential).toEqual({
...saveCredentialsResponse,
scopes: credentialScopes,
});
});
});
});