Skip to content

Commit

Permalink
fix(valid-expect): support async expect in ternary statements (#833)
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath authored Apr 26, 2021
1 parent 1fee973 commit 7b7a396
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 3 deletions.
86 changes: 86 additions & 0 deletions src/rules/__tests__/valid-expect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,35 @@ ruleTester.run('valid-expect', rule, {
return expect(functionReturningAPromise()).resolves.toEqual(1).then(() => expect(Promise.resolve(2)).resolves.toBe(1));
});
`,
dedent`
expect.extend({
toResolve(obj) {
return this.isNot
? expect(obj).toBe(true)
: expect(obj).resolves.not.toThrow();
}
});
`,
dedent`
expect.extend({
toResolve(obj) {
return this.isNot
? expect(obj).resolves.not.toThrow()
: expect(obj).toBe(true);
}
});
`,
dedent`
expect.extend({
toResolve(obj) {
return this.isNot
? expect(obj).toBe(true)
: anotherCondition
? expect(obj).resolves.not.toThrow()
: expect(obj).toBe(false)
}
});
`,
{
code: 'expect(1).toBe(2);',
options: [{ maxArgs: 2 }],
Expand Down Expand Up @@ -369,6 +398,63 @@ ruleTester.run('valid-expect', rule, {
],
},

{
code: dedent`
expect.extend({
toResolve(obj) {
this.isNot
? expect(obj).toBe(true)
: expect(obj).resolves.not.toThrow();
}
});
`,
errors: [
{
column: 9,
endColumn: 43,
messageId: 'asyncMustBeAwaited',
},
],
},
{
code: dedent`
expect.extend({
toResolve(obj) {
this.isNot
? expect(obj).resolves.not.toThrow()
: expect(obj).toBe(true);
}
});
`,
errors: [
{
column: 9,
endColumn: 43,
messageId: 'asyncMustBeAwaited',
},
],
},
{
code: dedent`
expect.extend({
toResolve(obj) {
this.isNot
? expect(obj).toBe(true)
: anotherCondition
? expect(obj).resolves.not.toThrow()
: expect(obj).toBe(false)
}
});
`,
errors: [
{
column: 9,
endColumn: 43,
messageId: 'asyncMustBeAwaited',
},
],
},

// expect().resolves
{
code:
Expand Down
15 changes: 12 additions & 3 deletions src/rules/valid-expect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,23 @@ const isAcceptableReturnNode = (
node: TSESTree.Node,
allowReturn: boolean,
): node is
| TSESTree.ConditionalExpression
| TSESTree.ArrowFunctionExpression
| TSESTree.AwaitExpression
| TSESTree.ReturnStatement =>
(allowReturn && node.type === AST_NODE_TYPES.ReturnStatement) ||
[
| TSESTree.ReturnStatement => {
if (allowReturn && node.type === AST_NODE_TYPES.ReturnStatement) {
return true;
}

if (node.type === AST_NODE_TYPES.ConditionalExpression && node.parent) {
return isAcceptableReturnNode(node.parent, allowReturn);
}

return [
AST_NODE_TYPES.ArrowFunctionExpression,
AST_NODE_TYPES.AwaitExpression,
].includes(node.type);
};

const isNoAssertionsParentNode = (node: TSESTree.Node): boolean =>
node.type === AST_NODE_TYPES.ExpressionStatement ||
Expand Down

0 comments on commit 7b7a396

Please sign in to comment.