Stub external libraries used in invoked Supabase edge functions

  Kiến thức lập trình

I’ve got a Supabase edge function doing some speech-to-text using OpenAI JS library.

I have a unit test and I want to stub the call to OpenAI, so I don’t pay a lot of money every time I run my tests.

How can I achieve that, using Sinon or Deno stubbing?

This is what I’ve got so far, the edge function:

import OpenAI from "npm:openai";

const apiKey = Deno.env.get('OPENAI_API_KEY')
const openai = new OpenAI({
  apiKey: apiKey
});

async function requestHandler(req: Request): Response {
    const { bucket = 'campaigns', campaign_id, call_id, speaker, name } = await req.json()

    const { data, error } = await supabaseAdmin
        .storage
        .from(bucket)
        .createSignedUrl(`${campaign_id}/calls/${call_id}/audios/${name}`, 60);

    if (data) {
        const fileResponse = await fetch(data.signedUrl);

        if (fileResponse) {
            // generate text
            const transcription = await openai.audio.transcriptions.create({
                'file': fileResponse,
                'model': 'whisper-1',
                "prompt": "Vokall, Vokall.io"
            });

            return new Response(transcription.text, {
                headers: { 'Content-Type': 'text/plain' }
            });
        }
    }
}

Deno.serve(requestHandler);

The unit test:

import sinon from "npm:sinon";
import {
  afterAll,
  beforeAll,
  describe,
  it,
} from "https://deno.land/[email protected]/testing/bdd.ts";
import { assertEquals } from "https://deno.land/[email protected]/assert/assert_equals.ts";
import { createClient, SupabaseClient } from 'https://esm.sh/@supabase/[email protected]'
import { faker } from 'https://esm.sh/@faker-js/faker';
import OpenAI from "npm:openai";

// Set up the configuration for OpenAI
const apiKey = "test-api-key";
const openai = new OpenAI({
  apiKey: apiKey
});

Deno.env.set('OPENAI_API_KEY', apiKey);

// Set up the configuration for the Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL') ?? ''
const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
const options = {
  auth: {
    autoRefreshToken: false,
    persistSession: false,
    detectSessionInUrl: false,
  },
}

const supabaseAdmin: SupabaseClient = createClient(supabaseUrl, supabaseKey, options);

describe('Stt', () => {
  const campaignId = faker.number.int({ min: 10, max: 100 });
  const callId = faker.number.int({ min: 10, max: 100 });
  const speaker = 'assistant';
  const bucketName = faker.string.alpha({ length: 10, casing: 'lower'});
  const fileName = faker.system.commonFileName('mp3')
  const filePath = `${campaignId}/calls/${callId}/audios/${fileName}`

  it("stt is successful", async () => {
    const transcribedText = "This is the transcribed text from openai.audio.transcriptions.create()";
    const requestBody = {
      bucket: bucketName,
      campaign_id: campaignId,
      call_id: callId,
      speaker: speaker,
      name: fileName,
    };

    const stubTranscription = sinon.stub(
      openai.audio.transcriptions,
      "create"
    ).resolves({ text: transcribedText }); // <= This doesn't work at all

    const { data, error } = await supabaseAdmin.functions.invoke('stt', {
      body: requestBody
    });

    assertEquals(data, transcribedText)

    stubTranscription.restore()
  });
});

In my unit test, I want to stub openai.audio.transcriptions.create. I tried with Sinon and also Deno stubbing, without success so far.

Any ideas on how to do that?

1

LEAVE A COMMENT