Skip to content

Commit

Permalink
Create deepLTranslate.test.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
ttsukagoshi committed Feb 7, 2024
1 parent 32a9c9b commit 1389241
Showing 1 changed file with 86 additions and 0 deletions.
86 changes: 86 additions & 0 deletions tests/deepLTranslate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { deepLTranslate } from '../src/sheetsl';

describe('deepLTranslate', () => {
beforeEach(() => {
global.PropertiesService = {
getUserProperties: jest.fn(() => ({
getProperty: jest.fn(() => 'SampleApiKey:fx'),
})),
} as unknown as GoogleAppsScript.Properties.PropertiesService;
global.encodeURIComponent = jest.fn(
(text: string) => text,
) as unknown as typeof encodeURIComponent;
});
afterEach(() => {
jest.clearAllMocks();
});
const mockSourceObjects = [
{
note: 'with source language specified',
sourceLang: 'EN-US',
targetLang: 'DE',
sourceText: 'Hello, World!',
translatedText: 'Hallo, Welt!',
},
{
note: 'without source language specified',
sourceLang: null,
targetLang: 'DE',
sourceText: 'Hello, World!',
translatedText: 'Hallo, Welt!',
},
{
note: 'in an array of strings',
sourceLang: null,
targetLang: 'DE',
sourceText: ['Hello, World!', 'Hello, World!'],
translatedText: ['Hallo, Welt!', 'Hallo, Welt!'],
},
];
it.each(mockSourceObjects)(
'should translate text $note',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
({ note, sourceLang, targetLang, sourceText, translatedText }) => {
global.UrlFetchApp = {
fetch: jest.fn(() => ({
getContentText: jest.fn(() =>
JSON.stringify({
translations: Array.isArray(translatedText)
? translatedText.map((text) => ({ text: text }))
: [{ text: translatedText }],
}),
),
getResponseCode: jest.fn(() => 200),
})),
} as unknown as GoogleAppsScript.URL_Fetch.UrlFetchApp;
const translated = deepLTranslate(sourceText, sourceLang, targetLang);
expect(translated).toStrictEqual(
Array.isArray(translatedText) ? translatedText : [translatedText],
);
expect(global.UrlFetchApp.fetch).toHaveBeenCalled();
},
);
const mockSourceObjectsError = [
{
note: 'when source text is null',
sourceLang: 'EN-US',
targetLang: 'DE',
sourceText: null,
},
{
note: 'when source text is empty',
sourceLang: 'EN-US',
targetLang: 'DE',
sourceText: '',
},
];
it.each(mockSourceObjectsError)(
'should throw an error $note',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
({ note, sourceLang, targetLang, sourceText }) => {
expect(() => deepLTranslate(sourceText, sourceLang, targetLang)).toThrow(
new Error('[SheetsL] Empty input.'),
);
},
);
});

0 comments on commit 1389241

Please sign in to comment.