如何测试从子组件调用的父方法?

问题描述 投票:0回答:1

我正在使用酶和玩笑,我想测试调用子道具时是否调用了父方法。

我有这样的东西

class Parent extends Component {

  method = () => {...}

  render() {

    <Child propMethod={method}/>
}
}

在测试中,我做这样的事情

let shallow;

function setup() {
    const props = {
        mockMethod: jest.fn()
    };

    const enzymeWrapper = shallow(<Parent {...props}/>);

    return {
        props,
        enzymeWrapper
    };
}
    beforeAll(() => {
        shallow = createShallow({ dive: true });
    });

describe('components', () => {
    describe('Child', () => {
        it('should call method', () => {
            const { enzymeWrapper, props } = setup()
            const component = enzymeWrapper.find(Child)
            component.prop('propMethod')();
            expect(props.mockMethod).toHaveBeenCalledTimes(1);

        })
    });
});

但是我得到

Expected number of calls: 1
Received number of calls: 0

测试结构来自Redux文档

here

reactjs jestjs enzyme
1个回答
0
投票

您的模拟方法没有针对子道具。从注释中,您可能想要做的是测试在调用该方法时是否具有有意义的副作用。如果最终要调度redux动作,请在调用child方法时测试该动作是否已调度。

如果您打算给当前测试施加任何对组件行为的实际约束,那么无论如何都必须做这样的事情,因此直接进行测试会更加直接和有意义。

© www.soinside.com 2019 - 2024. All rights reserved.