Unit Testing Custom Functions that Need CTX

Hi. We need to test several custom functions that use ctx, interacting with each other over a multi step process. How would you guys recommend we test our custom functions?

Would using mocha to call the live API be the only viable way right now?

Will invoke-local offer a ctx object soon? Is there a way to duplicate a workspace, so we can test on a live 8base environment without affecting the “production” workspace.

Thanks

Are you just using ctx to execute GraphQL requests? If so, you can stub this part pretty easily - here’s my implementation

import { GraphQLClient } from "graphql-request"

export default function buildCtx() {
  const path = require("path")
  require("dotenv").config({ path: path.resolve(process.cwd(), "..", ".env") })
  const { API_BASE_URL, API_TEMP_ACCESS_TOKEN } = process.env

  const client = new GraphQLClient(API_BASE_URL, {

    headers: {

      Authorization: `Bearer ${API_TEMP_ACCESS_TOKEN}`

    }

  })

  return {

    api: {

      async gqlRequest(query, variables) {

        try {

          return await client.request(query, variables)

        } catch (err) {

          console.log("Error fetching data", err)

          return { errors: err.response.errors }

        }

      }

    }

  }

}

And then in my event handler, just swap out ctx if undefined (showing top of file only):
import buildCtx from “…/…/utility/buildCtx”

export default async (event, context) => {

  const ctx = context || buildCtx()
  ...

I’d also love a duplicate workspace for testing purposes!
Would be so handy, and happy for that to use the same quota as prod too

3 Likes

Thanks man! This is definitely a step in the right direction :100:

1 Like