fix unit tests. add conversation model and add unit tests to it.

This commit is contained in:
Jordan Hewitt
2025-01-25 09:11:09 -08:00
parent 0c9daf8e4a
commit 82d9c9c523
21 changed files with 7127 additions and 4712 deletions

View File

@ -0,0 +1,32 @@
// conversation.test.ts
import { Translator } from '@/app/i18n/api';
import { Conversation, Message, Speaker } from '@/app/lib/conversation';
import { describe, beforeEach, it, expect, test } from '@jest/globals';
describe('Conversation', () => {
let conversation: Conversation;
beforeEach(() => {
const translator = new Translator("en", "sp");
const s1: Speaker = { language: "en", id: "s1" };
const s2: Speaker = { id: "s2", language: "sp" }
conversation = new Conversation(translator, s1, s2);
});
it('should add a message to the conversation', () => {
conversation.addMessage({ id: "s1", language: "en" }, "Hello");
expect(true).toEqual(false);
expect(conversation.length).toBe(1);
expect(conversation[0].speaker.id).toEqual("s1");
expect(conversation[0].text).toEqual("hello");
});
it('should translate the last message in the conversation', async () => {
conversation.addMessage({ id: "s1", language: "en" }, "Hello");
await conversation.translateLast();
expect(conversation[conversation.length - 1].translation).toEqual("Hollla");
});
});

38
app/lib/conversation.ts Normal file
View File

@ -0,0 +1,38 @@
import { Translator } from "../i18n/api";
export type Speaker = {
id: string,
language : string,
}
export class Message {
public translation? : string;
constructor (public text : string, public speaker : Speaker) {}
public async translate(translator : Translator, language? : string) {
this.translation = await translator.translate(this.text, language);
}
}
export class Conversation extends Array<Message> {
constructor (
private translator : Translator,
s1 : Speaker,
s2 : Speaker,
) {
super();
}
public addMessage(speaker : Speaker, text : string) {
this.push(new Message(text, speaker));
}
public async translateMessage(i : number) {
if (!this[i]) throw new Error(`${i} is not a valid message number`);
await this[i].translate(this.translator, this[i].speaker.language);
}
public async translateLast() {
return await this.translateMessage(this.length-1);
}
}