no-mocks-import.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _path = require("path");
  7. var _utils = require("./utils");
  8. const mocksDirName = '__mocks__';
  9. const isMockPath = path => path.split(_path.posix.sep).includes(mocksDirName);
  10. const isMockImportLiteral = expression => (0, _utils.isStringNode)(expression) && isMockPath((0, _utils.getStringValue)(expression));
  11. var _default = (0, _utils.createRule)({
  12. name: __filename,
  13. meta: {
  14. type: 'problem',
  15. docs: {
  16. category: 'Best Practices',
  17. description: 'Disallow manually importing from `__mocks__`',
  18. recommended: 'error'
  19. },
  20. messages: {
  21. noManualImport: `Mocks should not be manually imported from a ${mocksDirName} directory. Instead use \`jest.mock\` and import from the original module path.`
  22. },
  23. schema: []
  24. },
  25. defaultOptions: [],
  26. create(context) {
  27. return {
  28. ImportDeclaration(node) {
  29. if (isMockImportLiteral(node.source)) {
  30. context.report({
  31. node,
  32. messageId: 'noManualImport'
  33. });
  34. }
  35. },
  36. 'CallExpression[callee.name="require"]'(node) {
  37. const [arg] = node.arguments;
  38. if (arg && isMockImportLiteral(arg)) {
  39. context.report({
  40. node: arg,
  41. messageId: 'noManualImport'
  42. });
  43. }
  44. }
  45. };
  46. }
  47. });
  48. exports.default = _default;