Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(prefer-to-be): support negative numbers #1260

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/rules/__tests__/prefer-to-be.test.ts
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
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