代码之家  ›  专栏  ›  技术社区  ›  ismael oliva

如何测试通过props的函数

  •  -1
  • ismael oliva  · 技术社区  · 6 年前

    如果我有这样的组件

    import React from "react";
    
    const GettingStarted = ({ object }) => <Button onPress={() => object.next()} />;
    

    你怎么能开玩笑来测试呢 object.next() 在组件内部调用?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Katia Wheeler    6 年前

    基本思想是监视传递给 onPress . 然后,您将模拟 印刷机 事件,并检查是否使用任何参数调用了监视函数等,然后测试函数的实际输出。例如,如果函数将按钮中的文本从“单击我”更改为“单击!”,您将在单击前对第一个文本属性断言,然后检查更新的属性。

    笑话示例:

    const onPressSpy = jest.fn();
    
    const gettingStartedButton = shallow(<GettingStarted object={onPressSpy} />);
    
    expect(gettingStartedButton.find('button').children().text()).toBe('Click Me!');
    
    gettingStartedButton.find('button').simulate('press');
    expect(onPressSpy).toHaveBeenCalled();
    expect(gettingStartedButton.find('button').children().text()).toBe('Clicked!');
    
    推荐文章