Extract and set form values through the DOM—no frameworks required! https://github.com/TheoryOfNekomata/formxtra
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

71 рядки
1.8 KiB

  1. /// <reference types="cypress" />
  2. /// <reference types="cypress-jest-adapter" />
  3. import fs from 'fs'
  4. import path from 'path'
  5. type TestFn = (form: HTMLFormElement, after: Record<string, string> | string) => unknown
  6. export const setup = (template: string) => {
  7. if (typeof cy !== 'undefined') {
  8. return () => {
  9. cy.intercept({ url: '/' }, { fixture: `templates/${template}.html` });
  10. cy.intercept({ url: '/?*' }, { fixture: `templates/${template}.html` }).as('submitted');
  11. }
  12. }
  13. return async () => {
  14. const templatePath = path.join('test', 'fixtures', 'templates', `${template}.html`)
  15. const templateRaw = await fs.promises.readFile(templatePath)
  16. window.document.open()
  17. window.document.write(templateRaw.toString('utf-8'))
  18. window.document.close()
  19. }
  20. }
  21. export const test = (opFn: (wrapper: any) => unknown, testFn: TestFn, expectedValue: Record<string, string> | string) => {
  22. let form: HTMLFormElement
  23. if (typeof cy !== 'undefined') {
  24. cy
  25. .visit('/')
  26. .get('form')
  27. .then((formResult) => {
  28. [form] = Array.from(formResult);
  29. })
  30. opFn(cy)
  31. cy
  32. .wait('@submitted')
  33. .location('search')
  34. .then(search => {
  35. testFn(form, search)
  36. })
  37. } else {
  38. [form] = Array.from(window.document.getElementsByTagName('form'))
  39. testFn(form, expectedValue)
  40. }
  41. }
  42. export const makeSearchParams = (beforeValues: Record<string, unknown> | string) => {
  43. switch (typeof (beforeValues as unknown)) {
  44. case 'string':
  45. return new URLSearchParams(beforeValues as string)
  46. case 'object':
  47. return Object
  48. .entries(beforeValues)
  49. .reduce(
  50. (beforeSearchParams, [key, value]) => {
  51. const theValue = !Array.isArray(value) ? [value] : value
  52. theValue.forEach(v => {
  53. beforeSearchParams.append(key, v)
  54. })
  55. return beforeSearchParams
  56. },
  57. new URLSearchParams()
  58. )
  59. default:
  60. break
  61. }
  62. throw new TypeError('Invalid parameter.')
  63. }