Skip to content

Commit

Permalink
chore: add backend tests wip
Browse files Browse the repository at this point in the history
  • Loading branch information
kathleenkhy committed Mar 4, 2024
1 parent a7d15c8 commit aa47466
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 26 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import OpenAI from 'openai'
import { OpenAIClient } from '@azure/openai'

import {
generateFormFields,
Expand All @@ -9,28 +9,38 @@ import {
AssistanceModelTypeError,
} from '../admin-form.errors'

// Mock openai
jest.mock('openai', () => jest.fn())
const MockedOpenAIClient = jest.mocked(OpenAI)

const mockReturnValue = {
role: 'user',
content: 'dummy content',
}

// Mock azure openai
jest.mock('@azure/openai', () => {
return {
AzureKeyCredential: jest.fn().mockImplementation((apiKey) => {
return apiKey
}),
OpenAIClient: jest.fn().mockImplementation(() => {
return {
getChatCompletions: jest.fn().mockResolvedValue({
choices: [
{
message: {
role: 'user',
content: 'dummy content',
},
},
],
}),
}
}),
}
})

const MockedOpenAIClient = jest.mocked(OpenAIClient)

beforeEach(() => {
jest.clearAllMocks()
MockedOpenAIClient.prototype.chat = {
completions: {
create: jest.fn().mockResolvedValue({
choices: [
{
message: mockReturnValue,
},
],
}),
},
} as any
})

describe('admin-form.assistance.service', () => {
Expand Down Expand Up @@ -67,8 +77,8 @@ describe('admin-form.assistance.service', () => {
const type = 'prompt'
const content = 'Sample content'

// Mock OpenAI API throwing an error
MockedOpenAIClient.prototype.chat.completions.create = jest
// Mock Azure OpenAI API throwing an error
MockedOpenAIClient.prototype.getChatCompletions = jest
.fn()
.mockRejectedValue(new Error('Some random error message'))

Expand Down Expand Up @@ -119,7 +129,7 @@ describe('admin-form.assistance.service', () => {
const questions = 'sample questions'

// Mock OpenAI API throwing an error
MockedOpenAIClient.prototype.chat.completions.create = jest
MockedOpenAIClient.prototype.getChatCompletions = jest
.fn()
.mockRejectedValue(new Error('Some random error message'))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,7 @@ const endpoint = azureOpenAIConfig.endpoint
const azureApiKey = azureOpenAIConfig.apiKey
const deploymentId = azureOpenAIConfig.deploymentId

if (!endpoint || !azureApiKey) {
throw new Error(
'Azure OpenAI endpoint or API key is not defined in the environment variables',
)
}

const azureOpenAi = new OpenAIClient(
export const azureOpenAi = new OpenAIClient(
endpoint,
new AzureKeyCredential(azureApiKey),
)
Expand Down

0 comments on commit aa47466

Please sign in to comment.