question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

import async in jest.mock

See original GitHub issue

I’m trying to perform an import inside my jest mock to use a separate file to reproduce the same mock in several codes. Simulation below: `const listCache: Array<AdmintoolResponse> = [];

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

// MockAWS.default<Response>(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 noticed that my mock arrives as a promise in the code where I refer to dynamoDB, so I understand that this is why it doesn’t identify the mock parameter. here is my mock of dynamoDB:

`import { AWSError } from ‘aws-sdk’; import { DocumentClient } from ‘aws-sdk/clients/dynamodb’;

const MockAWS = <T>(list: Array<T>) => { 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<T> = 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; ` ``

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
sigveiocommented, Aug 12, 2021

Hey @rogeriodms! It looks like you might have misplaced some backticks for your code blocks, so your post is unfortunately very hard to read.

If you believe there is a bug in Jest, it would be helpful if you can provide either a repl.it demo or a minimal repository on GitHub. See https://stackoverflow.com/help/minimal-reproducible-example for information on how to create good reproductions.

Here are also a few useful resources if you have questions or need help:

0reactions
github-actions[bot]commented, Sep 13, 2021

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

An Async Example - Jest
Let's implement a module that fetches user data from an API and returns the user name. user.js. import request from './request ...
Read more >
Mocking asynchronous functions with Jest - SwC
To automatically mock an import in jest, you can simply call jest.mock . You pass to it the same string you would when...
Read more >
JestJS - Trying to Mock Async Await in Node JS Tests
I am using babel-jest and jest-cli. Below are my modules. I am getting to the first console.log, but the second console.log returns undefined...
Read more >
Mocking asynchronous functions with Jest - Nishant Kaushish
Lets try hitting a real API and use axios library as http client for making requests. //index.js import axios from "axios" function ...
Read more >
Mocking Asynchronous Functions with Jest - YouTube
Mocking is a fundamental skill in testing. It allows you to avoid testing parts of your code that are outside your control, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found