import async in jest.mock
See original GitHub issueI’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:
- Created 2 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
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:
#testing
channel in ReactifluxThis 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.