next-i18next单元测试错误“无法读取未定义的属性语言",带有链接和笑话 [英] next-i18next unit testing error 'Cannot read property language of undefined' with Link and jest
问题描述
next-i18next
使用它自己的Link
组件来与语言环境子路径兼容.
next-i18next
uses it's own Link
component to be compatible with locale sub-paths.
https://github.com/isaachinman/next-i18next
当我尝试简单的快照测试时,出现错误Cannot read property language of undefined
.
When I try a simple snapshot test I get the error 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
组件的情况下运行并通过了预期的测试.
The test runs and passes without the Link
component as expected.
我对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;
反正我可以解决此错误吗?
Is there anyway I can fix this error?
推荐答案
您应该使用i18nextProvider包装正在测试的组件.
You should wrap your component under test with i18nextProvider.
检查在Jest中插入I18next useTranslation钩子不会触发toHaveBeenCalled
修改
I18next具有特殊"标记.使得t
函数的语言(cimode
)总是返回给定的键,这样,在测试中,您可以在键上声明而不是在值上声明(可以更改,有时不能由开发人员更改).
Edit
I18next has a "special" languages (cimode
) which makes the t
function always return the given key, this way in tests you can assert on the key instead of the value (which can be changed, sometimes not by the developer).
这篇关于next-i18next单元测试错误“无法读取未定义的属性语言",带有链接和笑话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!