score:16

Accepted answer

you can mock non defaults like this:

jest.mock('a-module', () => ({
  __esmodule: true,
  default: () => 'blah',
  a: () => 'blah',
  b: () => 'blah'
}));

https://remarkablemark.org/blog/2018/06/28/jest-mock-default-named-export/

or use __mocks__

as an alternative you could create a file under __mocks__ folder next to the original module with the same name as the module:

a_module_folder > 
    a-module.js
    __mocks__ >
        a-module.js

and that mock should just export the mocked versions:

export const a = () => 'blah';
export const b = () => 'blah';

and then just mock like this:

jest.mock('a-module');

for node_modules just put __mocks__folder on the same level as node_modules

https://jestjs.io/docs/en/manual-mocks

score:2

if you have a react component which is not default export which is actually a good practice (since default exports should be avoided):

export function mycomponentx() {
    return (
        <div>...</div>
    );
}

you can mock it in jest easily:

jest.mock('path/to/mycomponentx', () => ({
  mycomponentx: () => <>mock_my_component_x</>,
}));

score:3

testing react components is mostly done with enzyme, if you are trying to do it only with jest you have probably picked the wrong tool. i can only guess why you need to mock a component, but most surely you will be able to achieve it with enzyme.

there is enzyme shallow rendering which is specifically created for testing react. jest itself is not capable of rendering components. the definition as per airbnb docs is:

shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behaviour of child components.

simply said it is going to render the tested component 1 level deep e.g.

// file2.js

import { mycomponent } from 'file1';
import { shallow } from 'enzyme';

describe('mycomponent', () => {
  it('should render shallowly my component', () => {
    const wrapper = shallow(<mycomponent />);
    console.log(wrapper.debug()); 
    // output:
    //   <div>
    //     <a />
    //     <b />
    //   </div>
    // note: even if component <a /> is consisting of some markup, 
    // it won't be rendered 
  });
});

essentially you don't need to mock any of its dependent components, these are already mocked with enzyme shallow()

what you can do instead is test when you pass certain props to <mycomponent />, dependent components <a /> and <b /> are receiving expected props.

const wrapper = shallow(<mycomponent foo={1} bar={2} />);
expect(wrapper.find('a').props().foo).toequal(1);
expect(wrapper.find('b').props().bar).toequal(2);

Related Query

More Query from same tag