Search code examples
reactjsjestjsreact-i18next

testing object returned from useTranslation


I have the following code in my element:

ItemComponent

  const { t } = useTranslation('myjson')
  const myobject = t('myobject', { returnObjects: true })
  const renderContent = () => {
    return myobject.map(item => {
        return (<Item key={item} onClick={() => props.handleClick(item.name)}> <Icon type={item.iconType} />{item.name}</Item>)
      }
    })
  }

ItemComponent.test.js


it("renders without crashing", () => {
    const div = document.createElement("div");
    ReactDOM.render(<ItemComponent></ItemComponent>,div);
})

myjson

{
 "myobject":[
      
        {
          "name": "Name1",
          "iconType": "Icon1"
        },
        {
          "name": "Name2",
          "iconType": "Icon2"
        }
      ]
}

and a simple render test but when I run the test I receive the error myobject.map is not a function is there a way to properly test this? Not sure why I am getting this error so I dont know what to research or try

I've tried let entries = Object.keys(myobject).map((key)=>[Number(key), mybject[key]]) and then console.log("entries",typeof entries);

this still returns an object


Solution

  • Since in the code I was returning the objects, I need to mock that object along with use translation:

    const mock = {
     "myobject":[
          
            {
              "name": "Name1",
              "iconType": "Icon1"
            },
            {
              "name": "Name2",
              "iconType": "Icon2"
            }
          ]
    }
    
    jest.mock('react-i18next', ()=>({
       useTranslation: () => {
       return {
          t:(str)=>mock,
          i18:{
             changeLanguage: () => new Promise(()=>mock.myobject)
          }
        }
     }
    })