Reputation: 95
I have a functional react component and I want to change a property value inside the component in an enzyme unit test (in my case the ready
attribute). The unit test should use shallow
to avoid rendering any children components.
Here is the simplified component code:
import {useTranslation} from 'react-i18next';
// ...
const MyComponent: React.FC<IProps> = (props: IProps) => {
const {t, ready} = useTranslation('my-translation-namespace');
// ...
return (
<React.Fragment>
{ready &&
<div className="my-component">some more content...</div>
}
</React.Fragment>)
};
export default MyComponent;
And this is the corresponding test:
describe('MyComponent', () => {
let component: ShallowWrapper;
it('should be displayed', () => {
component = shallow(<MyComponent/>);
// HERE I WOULD LIKE TO SET: component.ready = true
expect(component.find('.my-component').length).toBe(1);
});
});
Any idea how to change the ready
attribute to true in my test?
Upvotes: 1
Views: 248
Reputation: 2175
This can be accomplished by mocking the react-i18next
module with jest.
const mockT = jest.fn((a) => a)
const mockReady = true
jest.mock('react-i18next', () =>
jest.fn().mockImplementation(() => ({
useTranslation: () => ({ t: mockT, ready: mockReady })
}))
);
Take a look at the documentation or this article if you are using ES modules or this answer for other options.
edit: use module factory for second param of jest.mock
instead if passing a plain object.
Upvotes: 2