utils.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { nextTick } from 'vue'
  3. import type { MockGraphQLInstance } from './mock-graphql-api'
  4. export const waitForTimeout = async (milliseconds = 0) => {
  5. return new Promise((resolve) => {
  6. setTimeout(resolve, milliseconds)
  7. })
  8. }
  9. export const waitForNextTick = async (withTimeout = false) => {
  10. if (withTimeout) {
  11. await nextTick()
  12. return new Promise((resolve) => {
  13. setTimeout(resolve, 0)
  14. })
  15. }
  16. return nextTick()
  17. }
  18. export const waitUntil = async (
  19. condition: () => unknown,
  20. msThreshold = 1000,
  21. ) => {
  22. return new Promise<void>((resolve, reject) => {
  23. const start = Date.now()
  24. const max = start + msThreshold
  25. const interval = setInterval(() => {
  26. if (condition()) {
  27. clearInterval(interval)
  28. resolve()
  29. }
  30. if (max < Date.now()) {
  31. clearInterval(interval)
  32. reject(new Error('Timeout'))
  33. }
  34. }, 30)
  35. })
  36. }
  37. export const waitUntilApisResolved = (...mockApis: MockGraphQLInstance[]) => {
  38. return waitUntil(() => mockApis.every((mock) => mock.calls.resolve))
  39. }
  40. // The apollo cache always asks for a field, even if it's marked as optional
  41. // this function returns a proxy that will return "null" on properties not defined
  42. // in the initial object.
  43. export const nullableMock = <T extends object>(obj: T): T => {
  44. const skipProperties = new Set(['_id', 'id', Symbol.toStringTag])
  45. return new Proxy(obj, {
  46. get(target, prop, receiver) {
  47. if (!Reflect.has(target, prop) && !skipProperties.has(prop)) {
  48. return null
  49. }
  50. const value = Reflect.get(target, prop, receiver)
  51. if (Array.isArray(value)) {
  52. return value.map(nullableMock)
  53. }
  54. if (typeof value === 'object' && value !== null) {
  55. return nullableMock(value)
  56. }
  57. return value
  58. },
  59. })
  60. }