From 557dd394a4535276a4c6fa046bfb525f4c412800 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Hekrla=20=28Heky=29?= Date: Wed, 5 Oct 2022 20:13:53 +0200 Subject: [PATCH] fix(prefer-to-be): support negative numbers (#1260) --- src/rules/__tests__/prefer-to-be.test.ts | 11 +++++++++++ src/rules/prefer-to-be.ts | 9 ++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/rules/__tests__/prefer-to-be.test.ts b/src/rules/__tests__/prefer-to-be.test.ts index 0e62a1a70..545b9c857 100644 --- a/src/rules/__tests__/prefer-to-be.test.ts +++ b/src/rules/__tests__/prefer-to-be.test.ts @@ -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 });', @@ -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`);', @@ -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);', diff --git a/src/rules/prefer-to-be.ts b/src/rules/prefer-to-be.ts index acf26dbd0..339b20914 100644 --- a/src/rules/prefer-to-be.ts +++ b/src/rules/prefer-to-be.ts @@ -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