如何测试道具传递的功能

时间:2019-01-18 13:46:58

标签: reactjs testing jestjs enzyme

如果我有这样的组件

import React from "react";

const GettingStarted = ({ object }) => <Button onPress={() => object.next()} />;

您如何开玩笑地测试object.next()是否在组件内部被调用?

1 个答案:

答案 0 :(得分:1)

基本思想是监视传递给onPress的函数。然后,您将模拟按钮上的onPress事件,并检查是否使用任何参数等调用了spi on函数。然后,您将测试该函数的实际输出。因此,例如,如果该函数将按钮中的文本从“ Click Me”更改为“ Clicked!”,则可以在单击之前对第一个text属性进行断言,然后检查更新的文本。

开玩笑的例子:

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!');
相关问题