Skip to content

Instantly share code, notes, and snippets.

@devsheva
Created July 15, 2024 19:43
Show Gist options
  • Save devsheva/4258784c77651fe1b7080449b0052350 to your computer and use it in GitHub Desktop.
Save devsheva/4258784c77651fe1b7080449b0052350 to your computer and use it in GitHub Desktop.
(Deno.test): Improve Factory Object for async ops
export function promisifyFactoryObj<TFactory>(
obj: TFactory,
status = 200,
): Promise<Response> {
return Promise.resolve(
new Response(JSON.stringify(obj), { status }),
)
}
@devsheva
Copy link
Author

Example of use case could be when needing to mock an API response.
It can work with a single obj, or an array.

// usage ex.


interface User {
 id: number
 firstName: string
}

const fakeUsers = [{
  id: 1,
  firstName: 'Alex',

  }, 
  {
     id: 2,
     firstName: 'Mark',
  }
}]

stub(
      globalThis,
      'fetch',
      returnsNext([
        promisifyFactoryObj<User[]>(fakeUsers),
      ]),
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment