Skip to content

Commit

Permalink
fix(prefer-to-be): support negative numbers (#1260)
Browse files Browse the repository at this point in the history
  • Loading branch information
hekystyle authored Oct 5, 2022
1 parent 77a927c commit 557dd39
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/rules/__tests__/prefer-to-be.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ruleTester.run('prefer-to-be', rule, {
'expect(null).toBeNull();',
'expect(null).not.toBeNull();',
'expect(null).toBe(1);',
'expect(null).toBe(-1);',
'expect(null).toBe(...1);',
'expect(obj).toStrictEqual([ x, 1 ]);',
'expect(obj).toStrictEqual({ x: 1 });',
Expand Down Expand Up @@ -41,6 +42,11 @@ ruleTester.run('prefer-to-be', rule, {
output: 'expect(value).toBe(1);',
errors: [{ messageId: 'useToBe', column: 15, line: 1 }],
},
{
code: 'expect(value).toStrictEqual(-1);',
output: 'expect(value).toBe(-1);',
errors: [{ messageId: 'useToBe', column: 15, line: 1 }],
},
{
code: 'expect(value).toEqual(`my string`);',
output: 'expect(value).toBe(`my string`);',
Expand Down Expand Up @@ -311,6 +317,11 @@ new TSESLint.RuleTester({
output: 'expect(null).toBe(1 as unknown as string as unknown as any);',
errors: [{ messageId: 'useToBe', column: 14, line: 1 }],
},
{
code: 'expect(null).toEqual(-1 as unknown as string as unknown as any);',
output: 'expect(null).toBe(-1 as unknown as string as unknown as any);',
errors: [{ messageId: 'useToBe', column: 14, line: 1 }],
},
{
code: 'expect("a string").not.toStrictEqual("string" as number);',
output: 'expect("a string").not.toBe("string" as number);',
Expand Down
9 changes: 8 additions & 1 deletion src/rules/prefer-to-be.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@ const isFirstArgumentIdentifier = (
) => isIdentifier(getFirstMatcherArg(expectFnCall), name);

const shouldUseToBe = (expectFnCall: ParsedExpectFnCall): boolean => {
const firstArg = getFirstMatcherArg(expectFnCall);
let firstArg = getFirstMatcherArg(expectFnCall);

if (
firstArg.type === AST_NODE_TYPES.UnaryExpression &&
firstArg.operator === '-'
) {
firstArg = firstArg.argument;
}

if (firstArg.type === AST_NODE_TYPES.Literal) {
// regex literals are classed as literals, but they're actually objects
Expand Down

0 comments on commit 557dd39

Please sign in to comment.