Skip to content

Commit

Permalink
fix(prefer-to-be): support template literals (#1006)
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Dec 27, 2021
1 parent 4fe66ce commit aa428e6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
19 changes: 18 additions & 1 deletion src/rules/__tests__/prefer-to-be.test.ts
@@ -1,7 +1,13 @@
import { TSESLint } from '@typescript-eslint/experimental-utils';
import rule from '../prefer-to-be';
import { espreeParser } from './test-utils';

const ruleTester = new TSESLint.RuleTester();
const ruleTester = new TSESLint.RuleTester({
parser: espreeParser,
parserOptions: {
ecmaVersion: 2015,
},
});

ruleTester.run('prefer-to-be', rule, {
valid: [
Expand All @@ -16,6 +22,7 @@ ruleTester.run('prefer-to-be', rule, {
'expect("something");',
'expect(token).toStrictEqual(/[abc]+/g);',
"expect(token).toStrictEqual(new RegExp('[abc]+', 'g'));",
'expect(value).toEqual(dedent`my string`);',
],
invalid: [
{
Expand All @@ -33,6 +40,16 @@ ruleTester.run('prefer-to-be', rule, {
output: 'expect(value).toBe(1);',
errors: [{ messageId: 'useToBe', column: 15, line: 1 }],
},
{
code: 'expect(value).toEqual(`my string`);',
output: 'expect(value).toBe(`my string`);',
errors: [{ messageId: 'useToBe', column: 15, line: 1 }],
},
{
code: 'expect(value).toStrictEqual(`my ${string}`);',
output: 'expect(value).toBe(`my ${string}`);',
errors: [{ messageId: 'useToBe', column: 15, line: 1 }],
},
{
code: 'expect(loadMessage()).resolves.toStrictEqual("hello world");',
output: 'expect(loadMessage()).resolves.toBe("hello world");',
Expand Down
15 changes: 9 additions & 6 deletions src/rules/prefer-to-be.ts
Expand Up @@ -35,10 +35,16 @@ const isFirstArgumentIdentifier = (
name: string,
) => isIdentifier(getFirstArgument(matcher), name);

const isPrimitiveLiteral = (matcher: ParsedEqualityMatcherCall): boolean => {
const shouldUseToBe = (matcher: ParsedEqualityMatcherCall): boolean => {
const firstArg = getFirstArgument(matcher);

return firstArg.type === AST_NODE_TYPES.Literal && !('regex' in firstArg);
if (firstArg.type === AST_NODE_TYPES.Literal) {
// regex literals are classed as literals, but they're actually objects
// which means "toBe" will give different results than other matchers
return !('regex' in firstArg);
}

return firstArg.type === AST_NODE_TYPES.TemplateLiteral;
};

const getFirstArgument = (matcher: ParsedEqualityMatcherCall) => {
Expand Down Expand Up @@ -164,10 +170,7 @@ export default createRule({
return;
}

if (
isPrimitiveLiteral(matcher) &&
matcher.name !== EqualityMatcher.toBe
) {
if (shouldUseToBe(matcher) && matcher.name !== EqualityMatcher.toBe) {
reportPreferToBe(context, '', matcher);
}
},
Expand Down

0 comments on commit aa428e6

Please sign in to comment.