Reputation: 21
I'm doing a function which scan a table and the I use this function inside other in order to execute an elimination of data. When I do the unit test and I try to mock the scanCommand, it always send me undefined values as resolves doesn't return the data I mocked. It's nodejs with mocha-sinon project. My code is similar to this: repository.ts
public async scanData(
length: number,
tableName: string,
attributesToGet: string[],
client: DynamoDBClient
): Promise<ScanCommandOutput> {
const dynamoDBDDocClientOrigin = DynamoDBDocumentClient.from(client);
const inputScan: ScanCommandInput = {
TableName: tableName,
Select: 'SPECIFIC_ATTRIBUTES',
Limit: length,
ProjectionExpression: `${attributesToGet[POSITION_TYP_DOC]},${attributesToGet[POSITION_NUM_DOC]}`,
};
const scanCommand = new ScanCommand(inputScan);
return dynamoDBDDocClientOrigin.send(scanCommand);
}
The function which uses inside the other:
public async deleteData(
tableName: string,
attributesKeys: string[],
client: DynamoDBClient
): Promise<IResponseDelete | IResponseErrorCopyOrDelete> {
const repository = new DynamoDBRepositoryCollections();
const dynamoDBDDocClientOrigin = DynamoDBDocumentClient.from(client);
const resultDescribeTable = await repository.getDescribeTable(tableName, client);
if (resultDescribeTable.Table?.ItemCount) {
const contador = resultDescribeTable.Table?.ItemCount;
try {
for (let i = contador; i > 0; i -= 25) {
let dataToDelete = await repository.scanDataByLength(
25,
tableName,
attributesKeys,
client
);
const inputToDelete = await repository.batchDeleteInputObjectGenerator(
dataToDelete,
25,
tableName
);
const command = new BatchWriteItemCommand(inputToDelete);
if (dataToDelete.ScannedCount !== 0) {
await dynamoDBDDocClientOrigin.send(command);
}
}
return this.copyAndDeleteResponseMapper.mapResponseDelete(contador);
} catch (e: any) {
return this.mapper.mapError(e, 'Eliminado');
}
} else {
return this.mapper.mapError('Error por contador', 'Eliminado');
}
}
My test:
it('it should delete items when scanCommand is returning data in success way', async () => {
const dynamodbClientDelete = new DynamoDBClient({});
const ddbMockDelete = mockClient(dynamodbClienteDelete);
ddbMockDelete
.on(DescribeTableCommand)
.resolves(mockDescribeTable)
.on(ScanCommand).resolves(dataScannedMock) //Here resolves undefined
.on(BatchWriteItemCommand).resolves(mockBatchWrite);
const result = await repository.deleteData(
'TableName',
[attribute1, atributte2],
dynamodbClientDelete
);
expect(result.status).to.be.equal(200)
});
I tried manage the scan command with new stub and also configure the function with the responsibility of scanning also as a stub but in any cases always I received an undefined return. Thanks in advance for some advices.
Upvotes: 2
Views: 179