requiredValidation.spec.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitFrameworkContext } from '@formkit/core'
  3. import { createNode } from '@formkit/core'
  4. import requiredValidation from '../global/requiredValidation.ts'
  5. const createInput = (props: any = {}) => {
  6. const originalSchema = vi.fn()
  7. const inputNode = createNode({
  8. type: 'input',
  9. value: 'Test node',
  10. props: {
  11. definition: { type: 'input', schema: originalSchema },
  12. ...props,
  13. },
  14. })
  15. inputNode.context = {
  16. fns: {},
  17. } as FormKitFrameworkContext
  18. return inputNode
  19. }
  20. describe('requiredValidation', () => {
  21. it('doesnt add validation rule', () => {
  22. const inputNode = createInput({})
  23. requiredValidation(inputNode)
  24. expect(inputNode.props.validation).not.toBe('required')
  25. })
  26. it('adds validation rule', () => {
  27. const inputNode = createInput({
  28. required: true,
  29. })
  30. requiredValidation(inputNode)
  31. expect(inputNode.props.validation).toBe('required')
  32. })
  33. it('appends validation rule to string', () => {
  34. const inputNode = createInput({
  35. required: true,
  36. validation: 'number',
  37. })
  38. requiredValidation(inputNode)
  39. expect(inputNode.props.validation).toBe('number|required')
  40. })
  41. it('change initial validation prop value', () => {
  42. const inputNode = createInput({
  43. required: true,
  44. validation: 'number',
  45. })
  46. requiredValidation(inputNode)
  47. expect(inputNode.props.validation).toBe('number|required')
  48. // Change prop value
  49. inputNode.props.validation = 'email'
  50. expect(inputNode.props.validation).toBe('email|required')
  51. })
  52. it('appends validation rule to array', () => {
  53. const inputNode = createInput({
  54. required: true,
  55. validation: [['number']],
  56. })
  57. requiredValidation(inputNode)
  58. expect(inputNode.props.validation).toEqual([['number'], ['required']])
  59. })
  60. it('required prop removed from input', () => {
  61. const inputNode = createInput({
  62. required: true,
  63. validation: [['number']],
  64. })
  65. requiredValidation(inputNode)
  66. inputNode.props.required = false
  67. expect(inputNode.props.validation).toEqual([['number']])
  68. })
  69. it('required prop removed from string', () => {
  70. const inputNode = createInput({
  71. required: true,
  72. validation: 'number',
  73. })
  74. requiredValidation(inputNode)
  75. inputNode.props.required = false
  76. expect(inputNode.props.validation).toBe('number')
  77. })
  78. })