jsx-key.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @fileoverview Report missing `key` props in iterators/collection literals.
  3. * @author Ben Mosher
  4. */
  5. 'use strict';
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const rule = require('../../../lib/rules/jsx-key');
  10. const RuleTester = require('eslint').RuleTester;
  11. const parserOptions = {
  12. ecmaVersion: 2018,
  13. sourceType: 'module',
  14. ecmaFeatures: {
  15. jsx: true
  16. }
  17. };
  18. // ------------------------------------------------------------------------------
  19. // Tests
  20. // ------------------------------------------------------------------------------
  21. const ruleTester = new RuleTester({parserOptions});
  22. ruleTester.run('jsx-key', rule, {
  23. valid: [
  24. {code: 'fn()'},
  25. {code: '[1, 2, 3].map(function () {})'},
  26. {code: '<App />;'},
  27. {code: '[<App key={0} />, <App key={1} />];'},
  28. {code: '[1, 2, 3].map(function(x) { return <App key={x} /> });'},
  29. {code: '[1, 2, 3].map(x => <App key={x} />);'},
  30. {code: '[1, 2, 3].map(x => { return <App key={x} /> });'},
  31. {code: '[1, 2, 3].foo(x => <App />);'},
  32. {code: 'var App = () => <div />;'},
  33. {code: '[1, 2, 3].map(function(x) { return; });'},
  34. {code: 'foo(() => <div />);'}
  35. ],
  36. invalid: [{
  37. code: '[<App />];',
  38. errors: [{message: 'Missing "key" prop for element in array'}]
  39. }, {
  40. code: '[<App {...key} />];',
  41. errors: [{message: 'Missing "key" prop for element in array'}]
  42. }, {
  43. code: '[<App key={0}/>, <App />];',
  44. errors: [{message: 'Missing "key" prop for element in array'}]
  45. }, {
  46. code: '[1, 2 ,3].map(function(x) { return <App /> });',
  47. errors: [{message: 'Missing "key" prop for element in iterator'}]
  48. }, {
  49. code: '[1, 2 ,3].map(x => <App />);',
  50. errors: [{message: 'Missing "key" prop for element in iterator'}]
  51. }, {
  52. code: '[1, 2 ,3].map(x => { return <App /> });',
  53. errors: [{message: 'Missing "key" prop for element in iterator'}]
  54. }]
  55. });