frontAnswerer/cypress/support/commands.ts

73 lines
3.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Глобальная Map для кеширования переводов
const translationCache = new Map();
/**
* Загружает переводы для указанной локали с кешированием
* Если переводы уже загружены - возвращает из кеша
*/
Cypress.Commands.add("loadTranslations", (locale: string = "ru") => {
// Проверяем есть ли уже переводы в кеше для этой локали
if (translationCache.has(locale)) {
cy.log(`Переводы для локали "${locale}" уже загружены, используем кеш`);
return cy.wrap(translationCache.get(locale));
}
cy.log(`Загружаем переводы для локали: ${locale}`);
// Делаем HTTP запрос к файлу перевода
return cy
.request({
url: `/locales/${locale}.json`,
failOnStatusCode: true,
})
.then((response) => {
// Проверяем что запрос успешен
if (response.status !== 200) {
throw new Error(`Не удалось загрузить переводы для локали ${locale}. Status: ${response.status}`);
}
// Проверяем что ответ содержит данные
if (!response.body || typeof response.body !== "object") {
throw new Error(`Получен некорректный ответ для локали ${locale}`);
}
// Сохраняем переводы в кеш
translationCache.set(locale, response.body);
cy.log(
`Переводы для локали "${locale}" успешно загружены и закешированы. Ключей: ${Object.keys(response.body).length}`
);
return cy.wrap(response.body);
});
});
/**
* Получает конкретный перевод по ключу с использованием кеша
*/
Cypress.Commands.add("getTranslation", (key: string, locale: string = "ru") => {
// Сначала загружаем переводы (использует кеш если уже загружены)
return cy.loadTranslations(locale).then((translations) => {
// Проверяем что ключ существует в переводах
if (!translations.hasOwnProperty(key)) {
const availableKeys = Object.keys(translations).join(", ");
throw new Error(`Ключ перевода "${key}" не найден в локали "${locale}". Доступные ключи: ${availableKeys}`);
}
const translatedText = translations[key];
cy.log(`Перевод для ключа "${key}" в локали "${locale}": "${translatedText}"`);
return cy.wrap(translatedText as unknown as string);
});
});
/**
* Проверяет что элемент содержит правильный перевод
*/
Cypress.Commands.add("shouldHaveTranslation", (selector: string, key: string, locale: string = "ru") => {
// Получаем ожидаемый текст через кешированные переводы
cy.getTranslation(key, locale).then((expectedText) => {
// Проверяем что элемент содержит ожидаемый текст
cy.get(selector).should("contain", expectedText);
});
});