首页 > 解决方案 > componentWillMount 内部方法调用的 Jest 测试失败

问题描述

在我的组件中,我在this.props.foo()里面调用componentWillMount

public componentWillMount() {
    this.props.foo();
}

现在我想测试一下这个方法是否被调用,开玩笑:

it("should call startCountdown when mounted.", () => {
        const foo= jest.fn();
        const newProps: ComponentProps = {
            foo,
            ...defaultProps,
        };
        renderComponent(newProps);
        expect(foo).toHaveBeenCalled();
    });

renderComponent做这个:

const renderComponent= (props: ComponentProps = defaultProps) => {
        const rendered = TestRenderer.create(
            <Component {...props}/>);
        return rendered.root;
    };

这个测试怎么会失败?componentWillMount在 React Native中监视的正确方法是什么?

标签: reactjsunit-testingreact-nativejestjs

解决方案


        const newProps: ComponentProps = {
            ...defaultProps,
            foo,
        };

foo应该最后覆盖其他道具


推荐阅读