微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

next-i18next单元测试错误“无法读取未定义的属性语言”,带有链接和笑话

如何解决next-i18next单元测试错误“无法读取未定义的属性语言”,带有链接和笑话

next-i18next使用它自己的Link组件来与语言环境子路径兼容。

https://github.com/isaachinman/next-i18next

尝试简单的快照测试时,出现错误Cannot read property language of undefined

我的组件

import React from 'react';
import { TFunction } from 'next-i18next';
import { withTranslation,Link } from '../../../i18n';

interface HeaderProps {
  readonly t: TFunction;
}

const Header = ({ t }: HeaderProps): JSX.Element => {
  return (
    <>
      <Flex>
        <Box>
          <Link href="/">{t('home')}</Link>
        </Box>
      </Flex>
    </>
  );
};

export default withTranslation('common')(Header);

这是快照测试:

import React from 'react';
import { render,screen } from '@testing-library/react';
import Header from './Header';

describe('<Header/>',() => {
  test('it should render correctly',() => {
    const { container } = render(<Header />);
    expect(container.firstChild).toMatchSnapshot();
  });
});

测试在没有Link组件的情况下运行和通过。

我对i18n.ts的定义如下:

import path from 'path';
import NextI18Next from 'next-i18next';
import { publicRuntimeConfig } from './next.config';

const { localeSubpaths } = publicRuntimeConfig;

export const nextI18next = new NextI18Next({
  browserLanguageDetection: false,defaultNS: 'common',defaultLanguage: 'en',fallbackLng: 'en',otherLanguages: ['fr'],localeSubpaths,localePath: path.resolve('./public/static/locales'),});

export const {
  i18n,appWithTranslation,Link,withTranslation,Router,} = nextI18next;

反正我可以解决这个错误吗?

解决方法

您应该使用i18nextProvider包装正在测试的组件。

选中Stubbing I18next useTranslation hook in Jest doesn't trigger toHaveBeenCalled

修改 I18next具有一种“特殊”语言(cimode),它使t函数始终返回给定的键,这样,在测试中,您可以断言该键而不是值(可以更改,有时可以更改该值)不是由开发人员提供的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?