no-globals-in-created.test.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * @fileoverview disallow `window/document` in `created/beforeCreate`
  3. * @author Xin Du <clark.duxin@gmail.com>
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const rule = require('../no-globals-in-created')
  10. const RuleTester = require('eslint').RuleTester
  11. const parserOptions = {
  12. ecmaVersion: 2018,
  13. sourceType: 'module'
  14. }
  15. // ------------------------------------------------------------------------------
  16. // Tests
  17. // ------------------------------------------------------------------------------
  18. const ruleTester = new RuleTester()
  19. ruleTester.run('no-globals-in-created', rule, {
  20. valid: [
  21. {
  22. filename: 'test.vue',
  23. code: `
  24. export default {
  25. created() {
  26. const path = this.$route.path
  27. },
  28. beforeCreate() {
  29. const path = this.$route.params.foo
  30. }
  31. }
  32. `,
  33. parserOptions
  34. }
  35. ],
  36. invalid: [
  37. {
  38. filename: 'test.vue',
  39. code: `
  40. export default {
  41. created() {
  42. const path = window.location.pathname
  43. },
  44. beforeCreate() {
  45. const foo = document.foo
  46. }
  47. }
  48. `,
  49. errors: [{
  50. message: 'Unexpected window in created.',
  51. type: 'MemberExpression'
  52. }, {
  53. message: 'Unexpected document in beforeCreate.',
  54. type: 'MemberExpression'
  55. }],
  56. parserOptions
  57. },
  58. {
  59. filename: 'test.vue',
  60. code: `
  61. export default {
  62. created() {
  63. document.foo = 'bar'
  64. },
  65. beforeCreate() {
  66. window.foo = 'bar'
  67. }
  68. }
  69. `,
  70. errors: [{
  71. message: 'Unexpected document in created.',
  72. type: 'MemberExpression'
  73. }, {
  74. message: 'Unexpected window in beforeCreate.',
  75. type: 'MemberExpression'
  76. }],
  77. parserOptions
  78. },
  79. {
  80. filename: 'test.vue',
  81. code: `
  82. export default {
  83. created() {
  84. return window.foo
  85. },
  86. beforeCreate() {
  87. return document.foo
  88. }
  89. }
  90. `,
  91. errors: [{
  92. message: 'Unexpected window in created.',
  93. type: 'MemberExpression'
  94. }, {
  95. message: 'Unexpected document in beforeCreate.',
  96. type: 'MemberExpression'
  97. }],
  98. parserOptions
  99. }
  100. ]
  101. })