no-string-refs.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * @fileoverview Prevent string definitions for references and prevent referencing this.refs
  3. * @author Tom Hastjarjanto
  4. */
  5. 'use strict';
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const rule = require('../../../lib/rules/no-string-refs');
  10. const RuleTester = require('eslint').RuleTester;
  11. const parserOptions = {
  12. ecmaVersion: 2018,
  13. sourceType: 'module',
  14. ecmaFeatures: {
  15. jsx: true
  16. }
  17. };
  18. require('babel-eslint');
  19. // ------------------------------------------------------------------------------
  20. // Tests
  21. // ------------------------------------------------------------------------------
  22. const ruleTester = new RuleTester({parserOptions});
  23. ruleTester.run('no-refs', rule, {
  24. valid: [{
  25. code: `
  26. var Hello = createReactClass({
  27. componentDidMount: function() {
  28. var component = this.hello;
  29. },
  30. render: function() {
  31. return <div ref={c => this.hello = c}>Hello {this.props.name}</div>;
  32. }
  33. });
  34. `,
  35. parser: 'babel-eslint'
  36. }
  37. ],
  38. invalid: [{
  39. code: `
  40. var Hello = createReactClass({
  41. componentDidMount: function() {
  42. var component = this.refs.hello;
  43. },
  44. render: function() {
  45. return <div>Hello {this.props.name}</div>;
  46. }
  47. });
  48. `,
  49. parser: 'babel-eslint',
  50. errors: [{
  51. message: 'Using this.refs is deprecated.'
  52. }]
  53. }, {
  54. code: `
  55. var Hello = createReactClass({
  56. render: function() {
  57. return <div ref="hello">Hello {this.props.name}</div>;
  58. }
  59. });
  60. `,
  61. parser: 'babel-eslint',
  62. errors: [{
  63. message: 'Using string literals in ref attributes is deprecated.'
  64. }]
  65. }, {
  66. code: `
  67. var Hello = createReactClass({
  68. render: function() {
  69. return <div ref={'hello'}>Hello {this.props.name}</div>;
  70. }
  71. });
  72. `,
  73. parser: 'babel-eslint',
  74. errors: [{
  75. message: 'Using string literals in ref attributes is deprecated.'
  76. }]
  77. }, {
  78. code: `
  79. var Hello = createReactClass({
  80. componentDidMount: function() {
  81. var component = this.refs.hello;
  82. },
  83. render: function() {
  84. return <div ref="hello">Hello {this.props.name}</div>;
  85. }
  86. });
  87. `,
  88. parser: 'babel-eslint',
  89. errors: [{
  90. message: 'Using this.refs is deprecated.'
  91. }, {
  92. message: 'Using string literals in ref attributes is deprecated.'
  93. }]
  94. }]
  95. });