Vue 3 的 Cypress 测试以检查 i18n 语言转换器

问题描述 投票:0回答:1

在我的 Vue 3 应用程序中,用户可以为自己制作多语言页面。他们可以决定其页面上可用的语言。可用的语言是从 API 加载的。

语言在 Pinia 存储中加载,LanguageSwitcher.vue 组件根据浏览器设置、URL 中的语言变量、默认区域设置和可用语言加载默认语言。所有这些都需要严格的赛普拉斯测试,其中之一是确保页面上显示的所选语言实际上是所选的语言。但是我如何从 Cypress 的 i18n 中获取当前选择的语言?

我的LanguageSwitcher.vue组件(没有设置初始语言的逻辑)

</script>
<template>
  <div data-testid="localeSwitcher">
    <span v-if="getAvailableLocales().length > 1">
      <span v-for="(locale, i) in getAvailableLocales()" :key="`locale-${locale}`">
        <span v-if="i != 0" class="has-text-warning-dark"> | </span>
        <a  @click="setLocale(locale)" :class="[{ 'has-text-weight-bold' : ($i18n.locale === locale)}, 'has-text-warning-dark']">
          {{ locale.toUpperCase() }}
        </a>
      </span>
    </span>
  </div>
</template>

我的测试加载 i18n 并应该检查当前语言(尽管不知道如何做到这一点)

__test__/LanguageSwitcher.cy.js

describe('Test the LocaleSwitcher Languages selected',() => {
  let i18n       //<---thought if I declare it here maybe the test could access it
  beforeEach(() => {
    //list alle the available languages
    const availableMessages = { ru, en, ro }

    //load available languages
    i18n = createI18n({
      legacy: false,
      fallbackLocale: ro,
      locale: ro,
      globalInjection: true,
      messages: availableMessages
    })

    //mount component with the new i18n object
    cy.mount(LocaleSwitcher, { global: { plugins : [ i18n ]}})
  })


  it('Check if bold language is active language', () => {
    i18n.locale = 'ru'                    //<--- like so, but no
    //check of all links shown are unique
    cy.get('*[class^="has-text-weight-bold"]').should('have.length', 1)
    cy.get('*[class^="has-text-weight-bold"]').each(($a) => {
      expect($a.text()).to.have.string('RU')
    })
  })
})

我试图找到

global.plugins.i18n
在哪里,但我所有的搜索都是空的。那么我如何访问 Cypress 中当前安装的组件中的 i18n 并读取
i18n.locale

vuejs3 cypress vue-i18n
1个回答
0
投票

CypressVue 应用程序的上下文之外运行。
这意味着,直接访问 Vue 组件的内部状态或实例(例如您的 i18n 插件实例)并不简单。

使组件更具可测试性的一种方法是使用数据属性来存储可以在测试中轻松访问的状态信息。例如,您可以修改

LanguageSwitcher.vue
组件以包含反映当前区域设置的数据属性:

<a @click="setLocale(locale)" :data-current-locale="$i18n.locale === locale ? 'true' : 'false'" :class="[{'has-text-weight-bold': ($i18n.locale === locale)}, 'has-text-warning-dark']">
  {{ locale.toUpperCase() }}
</a>

在 Cypress 测试中,您可以选择具有正确属性的元素:

it('Check if bold language is active language', () => {
  // Assuming you have a way to change the language to 'ru'
  // For example, by simulating a click on the language switcher

  // After changing the language, check that the correct language is now active
  cy.get('[data-current-locale="true"]').should('have.length', 1);
  cy.get('[data-current-locale="true"]').should('contain', 'RU');
});

由于您正在测试 UI 组件,因此最端到端的测试方法是模拟用户交互以更改语言,然后检查 UI 是否反映了此更改。这意味着触发对语言切换器链接的点击并验证活动语言是否按预期突出显示:

it('Check if bold language is active language by UI interaction', () => {
  // Example: Click on the language switcher for Russian
  cy.contains('RU').click();

  // Now check if 'RU' is highlighted as the active language
  cy.get('*[class^="has-text-weight-bold"]').should('have.length', 1);
  cy.get('*[class^="has-text-weight-bold"]').should('contain', 'RU');
});

尽管 Vue CLI 不再积极开发,但它仍然是搭建 Vue.js 项目的流行工具。

如果您正在开发一个使用 Vue CLI 搭建的项目,并使用

@vue/cli-plugin-e2e-cypress
进行端到端测试,您可以使用
vue add e2e-cypress
在您的项目中设置 Cypress,包括默认配置和示例测试。
如果没有,为了将 Cypress 集成到基于 Vite 的项目中,您需要手动安装 Cypress 并配置它,因为 Vite 没有像 Vue CLI 那样的插件系统。

鉴于您的应用程序使用 Vue I18n 和 Pinia,您的测试需要与 UI 交互以更改语言并断言活动语言。虽然在 Cypress 测试中直接访问 Vue 的反应系统或 Vue I18n 等插件并不简单,但您可以像用户一样操作和断言 UI 状态更改。

您可以为您的

LanguageSwitcher.vue
组件编写 Cypress 测试,假设它呈现语言选项并突出显示活动语言,以模拟用户交互以更改语言,然后验证 UI 是否相应更新:

A

LanguageSwitcher.cy.js
将是:

describe('Language Switcher', () => {
  beforeEach(() => {
    // Visit the page where your LanguageSwitcher component is rendered
    cy.visit('/'); // Adjust the URL based on your application's routing

    // The following setup assumes your application already loads available languages
    // and sets a default language either from browser settings, URL params, or a default locale
  });

  it('switches language and updates the highlight', () => {
    // Example: Switch to Russian ('RU')
    // Assumes language options are rendered as clickable elements (e.g., buttons or links)
    cy.contains('RU').click();

    // Assert that 'RU' is now highlighted as the active language
    // That assumes you have a CSS class that highlights the active language
    cy.get('[data-testid="localeSwitcher"]')
      .find('.has-text-weight-bold')
      .should('contain', 'RU');

    // Optionally, verify that the page content updates to reflect the new language
    // That step depends on how your application renders localized content
    // cy.contains('Some content in Russian');
  });
});

测试与 Vue I18n 和 Pinia 相关的更复杂的行为(例如从 API 加载语言)需要在运行测试之前设置模拟响应或初始状态。这可以使用 Cypress 命令模拟 API 调用 或操作可能存储初始状态的浏览器本地存储和会话存储来完成。

© www.soinside.com 2019 - 2024. All rights reserved.