asynchronous import to jest.mock to keep the simulation file separate and reusable for other tests

Asked

Viewed 8 times

-1

I am trying to make an import into my play simulation to use a separate file to play the same simulation in multiple codes. Simulation below:

const listCache: Array = [];

jest.mock('aws-sdk', () => {
const MockAWS = import('../../mocks/DynamoRepositoryMock');

// MockAWS.default(listCache);
return MockAWS;
});

When I run my test, I get the following error:

Typeerror: Cannot read Property 'update' of Undefined

 11 | function configs() {
  12 |   console.log(AWS.config);
> 13 |   AWS.config.update({
     |              ^
  14 |     region: config.AWS.REGION,
  15 |     dynamodb: {
  16 |       endpoint: config.DYNAMO.ENDPOINT,

I realized that my mock comes as a promise in the code where I refer to dynamoDB, so I understand that’s why it doesn’t identify the mock parameter. here is my dynamoDB simulation:

import { AWSError } from 'aws-sdk';
import { DocumentClient } from 'aws-sdk/clients/dynamodb';

const MockAWS = (list: Array) => {
const config = {
update: jest.fn(() => ({
region: 'region-mock',
dynamodb: {
endpoint: 'dynamodb-mock',
},
})),
};
/*
Deve ser inicializado um array vazio
Por conta do hoisting do Jest, o jest.mock é executado antes mesmo dos imports

O array é inicializado vazio, e depois é feito o push dos dados de teste, caso contrário dá ruim.
*/
const listCache: Array = list;

return {
config,
DynamoDB: {
DocumentClient: jest.fn(() => ({
put: jest.fn((
params: DocumentClient.PutItemInput,
callback?: (err: AWSError, data: DocumentClient.PutItemOutput) => void,
) => {
listCache.push(
params.Item as T,
);

      callback(null, null);
    }),
    update: jest.fn((
      params: DocumentClient.UpdateItemInput,
      callback?: (err: AWSError, data: DocumentClient.UpdateItemOutput) => void,
    ) => {
      const keys = Object.entries(params.Key);
      const index = listCache.findIndex((t) => {
        let result = false;

        // eslint-disable-next-line no-restricted-syntax
        for (const key of keys) {
          result = t[key[0]] === key[1];
          if (!result) break;
        }
        return result;
      });

      const atts = Object.entries(params.ExpressionAttributeValues);

      atts.forEach((t) => {
        // eslint-disable-next-line prefer-destructuring
        listCache[index][t[0].substr(1)] = t[1];
      });

      callback(null, null);
    }),
    delete: jest.fn((
      params: DocumentClient.DeleteItemInput,
      callback?: (err: AWSError, data: DocumentClient.DeleteItemOutput) => void,
    ) => {
      const keys = Object.entries(params.Key);
      const index = listCache.findIndex((t) => {
        let result = false;

        // eslint-disable-next-line no-restricted-syntax
        for (const key of keys) {
          result = t[key[0]] === key[1];
          if (!result) break;
        }
        return result;
      });

      delete listCache[index];

      callback(null, null);
    }),
    get: jest.fn((
      params: DocumentClient.GetItemInput,
      callback?: (
        err: AWSError,
        data: DocumentClient.GetItemOutput
      ) => void,
    ) => {
      const keys = Object.entries(params.Key);
      const item = listCache.find((t) => {
        let result = false;

        // eslint-disable-next-line no-restricted-syntax
        for (const key of keys) {
          result = t[key[0]] === key[1];
          if (!result) break;
        }
        return result;
      });

      callback(null, {
        Item: item,
      });
    }),
    scan: jest.fn((
      params: DocumentClient.ScanInput,
      callback?: (
        err: AWSError,
        data: DocumentClient.ScanOutput
      ) => void,
    ) => {
      /*
            Com a implementação abaixo, N filtros podem ser usados
           */
      const keys = Object.entries(params.ExpressionAttributeValues);

      const result = params.ExpressionAttributeValues
        ? listCache.filter((t) => {
          // Mudar o nome dessa variável horrível
          let resultDois = false;
          // eslint-disable-next-line no-restricted-syntax
          for (const key of keys) {
            resultDois = t[key[0].substr(1)] === key[1];
            if (!resultDois) break;
          }
          return resultDois;
        }) : listCache;

      callback(null, {
        Items: result,
        Count: result.length,
      });
    }),
  })),
},
};
};

export default MockAWS;
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.