no-done-callback

Try in Playground
jestjsBest PracticeWarning

0

No tags

No CWE or CVE

This rule checks the function parameter of hooks & tests for use of the done argument, suggesting you return a promise instead.

View a similar ESLint rule, no-done-callback.

Ast Rule: function call


no-done-callback

How to write a rule
const TEST = 'test'
const HOOK = 'hook'
const FUNCTIONS_MAP = {
  it: TEST,
  test: TEST,
  describe: TEST,
  beforeAll: HOOK,
  beforeEach: HOOK,
  afterAll: HOOK,
  afterEach: HOOK,
};

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 jestFunctionType = FUNCTIONS_MAP[testFunctionName]

  if (!jestFunctionType) return;
  if (!node.arguments || !node.arguments.values || node.arguments.values.length === 0) return;

  // look at the first parameter in here
  if (jestFunctionType === HOOK) {
    if (node.arguments.values[0].value?.parameters?.values?.length > 0) {
      const cb = node.arguments.values[0].value?.parameters.values[0].name
      const error = buildError(
        cb.start.line,
        cb.start.col,
        cb.end.line,
        cb.end.col,
        "Disallow using a callback in asynchronous tests and hooks",
        "WARNING",
        "BEST_PRACTICE"
      );
      addError(error)
    }
  }

  // look at the second parameter in here
  if (jestFunctionType === TEST) {
    if (node.arguments.values[1].value?.parameters?.values?.length > 0) {
      const cb = node.arguments.values[1].value?.parameters.values[0].name
      const error = buildError(
        cb.start.line,
        cb.start.col,
        cb.end.line,
        cb.end.col,
        "Disallow using a callback in asynchronous tests and hooks",
        "WARNING",
        "BEST_PRACTICE"
      );
      addError(error)
    }
  }
}

done.spec.js

Expected test result: has error

beforeEach(done => {
  // ...
});

test('myFunction()', done => {
  // ...
});

test('myFunction()', function (done) {
  // ...
});

no-done.test.js

Expected test result: no error

No done callbacks

beforeEach(async () => {
  await setupUsTheBomb();
});

test('myFunction()', () => {
  expect(myFunction()).toBeTruthy();
});

test('myFunction()', () => {
  return new Promise(done => {
    expect(myFunction()).toBeTruthy();
    done();
  });
});
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.