Jest MockReact组件的实现

时间:2019-02-18 13:07:39

标签: javascript reactjs jestjs enzyme

我正在测试一个react组件,该组件将渲染另一个调用端点并返回一些数据的组件并显示出来,我想知道我该如何模拟调用端点并为每个测试返回虚拟数据的组件

这是我正在测试的组件

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
};

我想在测试中模拟MetadataValues,这是metadataValues.js文件

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
};

这是我的metaSelect.test.js文件

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();
    });
    
});

我猜我需要在MetadataValues.mockImplementation( )中添加一些内容
但我不确定我应该添加什么以正确模拟组件

2 个答案:

答案 0 :(得分:0)

如果您只需要在测试中使用一个模拟版本,就足够了:

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

如果您需要不同的模拟行为,则需要像这样模拟它

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>});
})


答案 1 :(得分:0)

使用shallow()代替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,
    });
});

这不仅以自然的方式进行嘲讽,而且具有一些好处

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);
})