【问题标题】:Jest test for method call inside componentWillMount failscomponentWillMount 内部方法调用的 Jest 测试失败
【发布时间】:2019-01-31 20:48:10
【问题描述】:

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

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

为什么这个测试失败了?在 React Native 中窥探 componentWillMount 的正确方法是什么?

【问题讨论】:

  • 什么是defaultProps,是否包括foo
  • @HermanStarikov 是的,确实如此。

标签: reactjs unit-testing react-native jestjs


【解决方案1】:
        const newProps: ComponentProps = {
            ...defaultProps,
            foo,
        };

foo 应该排在最后以覆盖其他道具

【讨论】:

  • 在我的辩护中,这都是 linter 的错,希望对象属性按字母顺序排列:)。谢谢!
  • 哈哈,linter 真的不应该那样做。
猜你喜欢
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2020-09-05
  • 2018-04-03
  • 2017-09-27
  • 1970-01-01
相关资源
最近更新 更多