index.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import * as assert from 'assert';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import { Linter } from 'tslint';
  5. import { parseConfigFile } from 'tslint/lib/configuration';
  6. const ruleNameList = fs
  7. .readdirSync(__dirname)
  8. .filter((filename) => fs.lstatSync(path.resolve(__dirname, filename)).isDirectory());
  9. describe('TSLint rules', () => {
  10. // 遍历每个目录
  11. ruleNameList.forEach((ruleName) => {
  12. const badFilepath = path.resolve(__dirname, `./${ruleName}/bad.ts`);
  13. const goodFilepath = path.resolve(__dirname, `./${ruleName}/good.ts`);
  14. describe(ruleName, () => {
  15. // bad.ts 存在时才会执行测试
  16. if (fs.existsSync(badFilepath)) {
  17. it('should have lint error for bad.ts', () => {
  18. const linter = new Linter(
  19. {
  20. fix: false
  21. }
  22. // 传入这个参数相当于 --project 运行
  23. // Linter.createProgram(
  24. // path.resolve(
  25. // __dirname,
  26. // `./${ruleName}/tsconfig.json`
  27. // )
  28. // )
  29. );
  30. // 执行 TSLint
  31. linter.lint(
  32. badFilepath,
  33. fs.readFileSync(badFilepath, 'utf-8'),
  34. parseConfigFile(require(`./${ruleName}/tslint.json`))
  35. );
  36. const lintResult = linter.getResult();
  37. // 错误数是否超过 0
  38. assert.ok(lintResult.errorCount > 0, 'Does not have lint error');
  39. // 错误规则是否是对应的测试规则
  40. lintResult.failures.forEach((failure) => {
  41. const failedRuleName = failure.getRuleName();
  42. assert.equal(
  43. failedRuleName,
  44. ruleName,
  45. `Failed rule '${failedRuleName}' does not match '${ruleName}'`
  46. );
  47. });
  48. });
  49. }
  50. // good.ts 存在时才会执行测试
  51. if (fs.existsSync(goodFilepath)) {
  52. it('should pass the lint for good.ts', () => {
  53. const linter = new Linter(
  54. {
  55. fix: false
  56. }
  57. // 传入这个参数相当于 --project 运行
  58. // Linter.createProgram(
  59. // path.resolve(
  60. // __dirname,
  61. // `./${ruleName}/tsconfig.json`
  62. // )
  63. // )
  64. );
  65. // 执行 TSLint
  66. linter.lint(
  67. goodFilepath,
  68. fs.readFileSync(path.resolve(goodFilepath), 'utf-8'),
  69. parseConfigFile(require(`./${ruleName}/tslint.json`))
  70. );
  71. const lintResult = linter.getResult();
  72. // 错误数是否等于 0
  73. assert.equal(lintResult.errorCount, 0, 'Have at least one error');
  74. });
  75. }
  76. });
  77. });
  78. });