I’m facing an issue that I can’t figure out how to resolve.
i’m trying to test this component:
import LabelIconButton from '../LabelIconButton'
import { PowerSettingsNew } from '@mui/icons-material'
export default function LabelIconButtonDisconnection() {
return <LabelIconButton title="déconnexion" icon={PowerSettingsNew} />
}
With this test:
import { render } from '@testing-library/react'
import LabelIconButton from '../LabelIconButton'
import { PowerSettingsNew } from '@mui/icons-material'
import LabelIconButtonDisconnection from './LabelIconButtonDisconnection'
jest.mock('../LabelIconButton', () => {
return jest.fn(() => <div>Mock LabelIconButton</div>)
})
describe('LabelIconButtonDisconnection', () => {
it('appelle le composant LabelIconButton avec les bonnes props', () => {
render(<LabelIconButtonDisconnection/>)
expect(LabelIconButton).toHaveBeenCalledWith({
title: 'déconnexion',
icon: PowerSettingsNew,
}, {})
})
})
I have this message error on the render of my test:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The issue is that no matter how much I check my imports (which seem correct to me), nothing works. It might be due to the icons-material. I’ve tried mocking it, but it doesn’t work.
Could you help me pls ?
2
Answers
I think the error is possibly being caused by how LabelIconButton in the test is being mocked. Since LabelIconButton is a default export, you can try using default export when mocking it.
using the __esModule: true and default: jest.fn() hopefully will ensure that the LabelIconButton import gets recognised by test.
Can you re-check your default imports vs non-default? We only see a very small part of the code, so it’s hard to be sure.
For example, I’m able to reproduce the error by doing this
import { LabelIconButtonDisconnection } from '../LabelIconButtonDisconnection'
when it should be
import LabelIconButtonDisconnection from '../LabelIconButtonDisconnection'
because it’s a default export.