no-test-prefixes

Try in Playground
jestjsBest PracticeWarning

0

No tags

No CWE or CVE

Jest allows you to choose how you want to define focused and skipped tests, with multiple permutations for each:

only and skip:

  • it.only, test.only, describe.only
  • it.skip, test.skip, describe.skip

f and x:

  • fit, ftest, fdescribe
  • xit, xtest, xdescribe

This rule suggests using an option from the only and skip list and warns when you do not.

View a similar ESLint rule, no-test-prefixes.

Ast Rule: function call


no-test-prefixes

How to write a rule
const TEST_FUNCTIONS_MAP = {
  xdescribe: "describe.skip",
  xtest: "test.skip",
  xit: "it.skip",
  fdescribe: "describe.only",
  ftest: "test.only",
  fit: "it.only",
};

function visit(node, filename, code) {
  // only run on .spec. or .test. files
  if (!filename.includes(".spec.") && !filename.includes(".test.")) return;

  if (node.functionName.astType !== "string") return;

  const testFunction = node.functionName
  const testFunctionName = testFunction?.value;
  const testFunctionNameReplacer = TEST_FUNCTIONS_MAP[testFunctionName];
  if (!testFunctionNameReplacer) return;

  const error = buildError(
    testFunction.start.line,
    testFunction.start.col,
    testFunction.end.line,
    testFunction.end.col,
    "Require using '.only' and '.skip' over 'f' and 'x'",
    "WARNING",
    "BEST_PRACTICE"
  );

  const edit = buildEdit(
    testFunction.start.line,
    testFunction.start.col,
    testFunction.end.line,
    testFunction.end.col,
    "update",
    testFunctionNameReplacer
  );

  const fix = buildFix(`Use "${testFunctionNameReplacer}" instead`, [edit]);

  addError(error.addFix(fix));
}

skip-and-only.test.js

Expected test result: no error

Tests using .skip and .only

it.only('foo')
test.only('foo');
describe.only('foo');
it.skip('foo');
test.skip('foo');
describe.skip('foo');

f-and-x.spec.js

Expected test result: has error

fit('foo');
ftest('foo');
fdescribe('foo');
xit('foo');
xtest('foo');
xdescribe('foo');
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.