Adam
Adam

Reputation: 2517

Jest MockImplementation of react component

I am testing a react component which renders another component which calls an endpoint and returns some data and is displayed, i want to know how i can mock the component that calls the endpoint and return dummy data for each test

This is the component i am testing

class MetaSelect extends React.Component {
    render() {
        console.log('metaselect render', MetadataValues);
        return (
             <MetadataValues type={this.props.type}> 
                {({ items, isLoading }) => (
                    <>
                        {isLoading ? (
                            <Icon variant="loadingSpinner" size={36} />
                        ) : (
                            <Select {...this.props} items={items} placeholder="Please select a value" />
                        )}
                    </>
                )}
            </MetadataValues> 
        );
    }
}

MetaSelect.propTypes = {
    type: PropTypes.string.isRequired
};

I want to mock the MetadataValues in my tests, this is the metadataValues.js file

class MetadataValues extends React.Component {
    state = {
        items: [],
        isLoading: true
    };

    componentDidMount() {
        this.fetchData();
    }

    fetchData = async () => {
        const items = await query(`....`);
        this.setState({ items, isLoading: false });
    };

    render() {
        return this.props.children({ items: this.state.items, isLoading: this.state.isLoading });
    }
}

MetadataValues.propTypes = {
    type: PropTypes.string.isRequired,
    children: PropTypes.func.isRequired
};

This is my metaSelect.test.js file

jest.mock('../MetadataValues/MetadataValues');


describe.only('MetaSelect component', () => {

    fit('Should display spinner when data isnt yet recieved', async () => {
        MetadataValues.mockImplementation( ()=> { <div>Mock</div>});
        
        const wrapper = mount(<MetaSelect type="EmployStatus"/>);          
        expect( wrapper.find('Icon').exists() ).toBeTruthy();
    });
    
});

Im guessing i need to add something in the MetadataValues.mockImplementation( )
but im not sure what i should add to mock the component correctly

Upvotes: 0

Views: 8307

Answers (2)

skyboyer
skyboyer

Reputation: 23763

what about using shallow() instead of mount()?

const mockedItems = [{.....}, {...}, ...];

it('shows spinner if data is loading', () => {
    const wrapper = shallow(<MetaSelect type={...} /*other props*/ />);
    const valuesChildren = wrapper.find(MetadataValues).prop('children');
    const renderResult = valuesChildren(mockedItems, true);
    expect(renderResult.find(Icon)).toHaveLength(1);
    expect(renderResult.find(Icon).props()).toEqual({
        variant: "LoadingSpinner", // toMatchSnapshot() may be better here
        size: 36,
    });
});

This not only makes mocking in natural way but also has some benefits

it('passes type prop down to nested MetadataValues', () => {
    const typeMocked = {}; // since it's shallow() incorrect `type` does not break anything
    const wrapper = shallow(<MetaSelect type={typeMocked} >);
    expect(wrapper.find(MetadataValues).prop('type')).toStrictEqual(typeMocked);
})

Upvotes: 0

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 111062

If you only need one version of the mock in your test this should be enough:

jest.mock('../MetadataValues/MetadataValues', ()=> ()=> <div>Mock</div>);

If you need to different mock behaviour you need to mock it like this

import MetadataValues from '../MetadataValues/MetadataValues'
jest.mock('../MetadataValues/MetadataValues', ()=> jest.fn());

it('does something', ()={
   MetadataValues.mockImplementation( ()=> { <div>Mock1</div>});
})

it('does something else', ()={
  MetadataValues.mockImplementation( ()=> { <div>Mock2</div>});
})


Upvotes: 2

Related Questions