I am getting the following error
ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was
object.
This error is encountered while I am trying to mock certain modules
My Main.test.js file
import React from 'react';
import { shallow } from 'enzyme';
jest.mock('../Elements', () =>
jest.fn().mockReturnValue({
SortIndicator: (props) => <div {...props}></div>,
ExchangeRate: (props) => <div {...props}></div>,
})
);
jest.mock('../../components/Default_Import', (props) => (
<div {...props}></div>
));
it('IT246 SearchListView is rendering without any error', async () => {
const MainContainer = await import('./MainContainer');
const wrapper = shallow(<MainContainer />)
})
My Main.js file
import { SortIndicator, ExchangeRate } from '../Elements';
export default class SearchListView extends React.Component {
render() {
return (
<>
<SortIndicator></SortIndicator>
<ExchangeRate></ExchangeRate>
</>
)
}
}
From the docs Importing defaults
When importing a default export with dynamic imports, it works a bit differently. You need to destructure and rename the "default" key from the returned object.
So, you need to dynamic import the ./MainContainer module like this:
describe('68279075', () => {
it('should pass', async () => {
const MainContainer = (await import('./main')).default;
const wrapper = shallow(<MainContainer />);
console.log(wrapper.debug());
});
});
An complete working example:
Main.jsx:
import React from 'react';
import { SortIndicator, ExchangeRate } from './Elements';
export default class SearchListView extends React.Component {
render() {
return (
<>
<SortIndicator></SortIndicator>
<ExchangeRate></ExchangeRate>
</>
);
}
}
Elements.jsx:
import React from 'react';
export function ExchangeRate() {
return <div>ExchangeRate</div>;
}
export function SortIndicator() {
return <div>SortIndicator</div>;
}
Main.test.jsx:
import React from 'react';
import { mount } from 'enzyme';
jest.mock('./Elements', () => ({
SortIndicator: (props) => <div {...props}>mocked SortIndicator</div>,
ExchangeRate: (props) => <div {...props}>mocked ExchangeRate</div>,
}));
describe('68279075', () => {
it('should pass', async () => {
const MainContainer = (await import('./main')).default;
const wrapper = mount(<MainContainer />);
console.log(wrapper.debug());
});
});
Debug messages:
PASS examples/68279075/Main.test.jsx (12.861 s)
68279075
✓ should pass (49 ms)
console.log
<SearchListView>
<SortIndicator>
<div>
mocked SortIndicator
</div>
</SortIndicator>
<ExchangeRate>
<div>
mocked ExchangeRate
</div>
</ExchangeRate>
</SearchListView>
at examples/68279075/Main.test.jsx:13:13
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.51 s
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