如何模拟 i18next-http-backend?

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

我在我的 React 应用程序中配置了 i18next-http-backend,如下所示:

import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import detector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'

i18n
    .use(Backend)
    .use(detector)
    .use(initReactI18next)
    .init({
        backend: {
            loadPath: `${process.env.PUBLIC_URL || ''}/locales/{{lng}}/{{ns}}.json`,
            addPath: null
        },
        fallbackLng: 'en',
        saveMissing: true,
        interpolation: {
            escapeValue: false // not needed for react as it escapes by default
        }
    })
export default i18n

在我的测试夹具中,我想模拟 i18n 方面。为此,我使用以下样板:

jest.mock('react-i18next', () => ({
    // this mock makes sure any components using the translate hook can use it without a warning being shown
    useTranslation: () => {
        return {
            t: (str: string) => str,
            i18n: {
                changeLanguage: () => new Promise(() => {})
            }
        }
    },
    initReactI18next: {
        type: '3rdParty',
        init: () => {}
    }
}))

测试还使用

msw
模拟 http 端点,这表明我的测试仍然想与 i18next 的 http 后端对话:

console.warn
      [MSW] Warning: captured a request without a matching request handler:
      
        • GET http://localhost/locales/en/translation.json

如何正确模拟 i18next,以防止它尝试与 http 后端通信?

reactjs jestjs mocking i18next i18next-http-backend
1个回答
1
投票

您可以通过从“i18next-http-backend”中模拟

Backend
来解决这个问题,例如

jest.mock('i18next-http-backend')

这将停止发出 HTTP 请求。

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