Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(valid-expect-in-promise): support await in arrays (#949)
  • Loading branch information
G-Rath committed Oct 14, 2021
1 parent 71b7e17 commit a62130c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 7 deletions.
22 changes: 22 additions & 0 deletions src/rules/__tests__/valid-expect-in-promise.test.ts
Expand Up @@ -120,6 +120,28 @@ ruleTester.run('valid-expect-in-promise', rule, {
return number + 1;
});
expect([await promise]).toHaveLength(1);
});
`,
dedent`
it('is valid', async () => {
const promise = loadNumber().then(number => {
expect(typeof number).toBe('number');
return number + 1;
});
expect([[await promise]]).toHaveLength(1);
});
`,
dedent`
it('is valid', async () => {
const promise = loadNumber().then(number => {
expect(typeof number).toBe('number');
return number + 1;
});
logValue(await promise);
});
`,
Expand Down
38 changes: 31 additions & 7 deletions src/rules/valid-expect-in-promise.ts
Expand Up @@ -143,6 +143,35 @@ const isPromiseMethodThatUsesValue = (
return isIdentifier(node.argument, name);
};

/**
* Attempts to determine if the runtime value represented by the given `identifier`
* is `await`ed within the given array of elements
*/
const isValueAwaitedInElements = (
name: string,
elements:
| TSESTree.ArrayExpression['elements']
| TSESTree.CallExpression['arguments'],
): boolean => {
for (const element of elements) {
if (
element.type === AST_NODE_TYPES.AwaitExpression &&
isIdentifier(element.argument, name)
) {
return true;
}

if (
element.type === AST_NODE_TYPES.ArrayExpression &&
isValueAwaitedInElements(name, element.elements)
) {
return true;
}
}

return false;
};

/**
* Attempts to determine if the runtime value represented by the given `identifier`
* is `await`ed as an argument along the given call expression
Expand All @@ -155,13 +184,8 @@ const isValueAwaitedInArguments = (

while (node) {
if (node.type === AST_NODE_TYPES.CallExpression) {
for (const argument of node.arguments) {
if (
argument.type === AST_NODE_TYPES.AwaitExpression &&
isIdentifier(argument.argument, name)
) {
return true;
}
if (isValueAwaitedInElements(name, node.arguments)) {
return true;
}

node = node.callee;
Expand Down

0 comments on commit a62130c

Please sign in to comment.