package.json
"moduleNameMapper": {
"i18next": "<rootDir>/__mocks__/i18nextMock.js"
}
i18n.js
import i18n from 'i18next'
import XHR from 'i18next-xhr-backend'
// import Cache from 'i18next-localstorage-cache'
import LanguageDetector from 'i18next-browser-languagedetector'
i18n
.use(XHR)
// .use(Cache)
.use(LanguageDetector)
.init({
fallbackLng: 'en',
// wait: true, // globally set to wait for loaded translations in translate hoc
lowerCaseLng: true,
load: 'languageOnly',
// have a common namespace used around the full app
ns: ['common'],
defaultNS: 'common',
debug: true,
// cache: {
// enabled: true
// },
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ',',
format: function (value, format, lng) {
if (format === 'uppercase') return value.toUpperCase()
return value
}
}
})
export default i18n
i18nextMock.js
/* global jest */
const i18next = jest.genMockFromModule('react-i18next')
i18next.t = (i) => i
i18next.translate = (c) => (k) => k
module.exports = i18next
For some reason the jest unit tests are not getting a component.
Here is a unit test:
import React from 'react'
import { Provider } from 'react-redux'
import { MemoryRouter } from 'react-router-dom'
import { mount } from 'enzyme'
import { storeFake } from 'Base/core/storeFake'
import Container from '../container'
describe('MyContainer (Container) ', () => {
let Component;
beforeEach(() => {
const store = storeFake({})
const wrapper = mount(
<MemoryRouter>
<Provider store={store}>
<Container />
</Provider>
</MemoryRouter>
)
Component = wrapper.find(Container)
});
it('should render', () => {
// Component is undefined here
expect(Component.length).toBeTruthy()
})
})
You don't need to mock the t
function, only the translate
one is required. For the second one, your usage of the parameters are confusing, also, you need to return a Component.
I was able to make it work on my project. Here are my mock file and my Jest configuration
Jest configuration
"moduleNameMapper": {
"react-i18next": "<rootDir>/__mocks__/reacti18nextMock.js"
}
The source code to mock react-i18next
/* global jest */
import React from 'react'
const react_i18next = jest.genMockFromModule('react-i18next')
const translate = () => Component => props => <Component t={() => ''} {...props} />
react_i18next.translate = translate
module.exports = react_i18next
I used Atemu's anwser in my jest tests, but ended up with the following one line in the mock:
module.exports = {t: key => key};
Also modified jest config as well since I import 't' from 'i18next':
"moduleNameMapper": {
"i18next": "<rootDir>/__mocks__/reacti18nextMock.js"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With