valid-describe.js 2.51 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
'use strict';

const { getDocsUrl, isDescribe, isFunction } = require('./util');

const isAsync = node => node.async;

const isString = node =>
  (node.type === 'Literal' && typeof node.value === 'string') ||
  node.type === 'TemplateLiteral';

const hasParams = node => node.params.length > 0;

const paramsLocation = params => {
  const [first] = params;
  const last = params[params.length - 1];
  return {
    start: {
      line: first.loc.start.line,
      column: first.loc.start.column,
    },
    end: {
      line: last.loc.end.line,
      column: last.loc.end.column,
    },
  };
};

module.exports = {
  meta: {
    docs: {
      url: getDocsUrl(__filename),
    },
  },
  create(context) {
    return {
      CallExpression(node) {
        if (isDescribe(node)) {
          if (node.arguments.length === 0) {
            return context.report({
              message: 'Describe requires name and callback arguments',
              loc: node.loc,
            });
          }

          const [name] = node.arguments;
          const [, callbackFunction] = node.arguments;
          if (!isString(name)) {
            context.report({
              message: 'First argument must be name',
              loc: paramsLocation(node.arguments),
            });
          }
          if (callbackFunction === undefined) {
            return context.report({
              message: 'Describe requires name and callback arguments',
              loc: paramsLocation(node.arguments),
            });
          }
          if (!isFunction(callbackFunction)) {
            return context.report({
              message: 'Second argument must be function',
              loc: paramsLocation(node.arguments),
            });
          }
          if (isAsync(callbackFunction)) {
            context.report({
              message: 'No async describe callback',
              node: callbackFunction,
            });
          }
          if (hasParams(callbackFunction)) {
            context.report({
              message: 'Unexpected argument(s) in describe callback',
              loc: paramsLocation(callbackFunction.params),
            });
          }
          if (callbackFunction.body.type === 'BlockStatement') {
            callbackFunction.body.body.forEach(node => {
              if (node.type === 'ReturnStatement') {
                context.report({
                  message: 'Unexpected return statement in describe callback',
                  node,
                });
              }
            });
          }
        }
      },
    };
  },
};