#How to mock `openai-node` with Vitest?

1 messages · Page 1 of 1 (latest)

oak star
#

Hello everyone,

I'm currently working on a project where I'm using the openai-node package to interact with the OpenAI API. I'm writing unit tests for my service class, OpenAIService, which uses the chat.completions.create() method from the OpenAI SDK.

Here's a snippet of my test setup:

import OpenAI from 'openai'
import {SpyInstance, afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
import OpenAIService from '../../lib/services/open-ai'

describe('OpenAIService', () => {
  let openAiService: OpenAIService
  let openAiSpy: SpyInstance

  beforeEach(() => {
    openAiService = new OpenAIService()
    openAiSpy = vi.spyOn(OpenAI.prototype.chat.completions, 'create')
  })

  afterEach(() => {
    openAiSpy.mockReset()
    vi.clearAllMocks()
  })

  // Rest of the test code...
})

I'm using Vitest for testing and I'm trying to mock the chat.completions.create() method using vi.spyOn(). However, I'm not sure if I'm doing it correctly since I'm getting this error from my test:

Cannot read properties of undefined (reading 'completions')
beforeEach(() => {
  openAiService = new OpenAIService()
  openAiSpy = vi.spyOn(OpenAI.prototype.chat.completions, 'create')
                                             ^
})

Can anyone provide some guidance on how to properly mock this method?

Any help would be greatly appreciated!

Thanks in advance!