如何测试一个功能被称为React Jest? [英] How to test a function is called in react jest?
本文介绍了如何测试一个功能被称为React Jest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的按钮位于组件内部,单击时会调用deleteData方法。
如何测试在按钮中单击笑话时是否调用deleteData方法?
I have my button inside a component, which calls a method deleteData on click. How do I test the deleteData method is called on the button click in jest?
<Modal.Footer>
<Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>
deleteData() {
{/* TODO :*/}
}
推荐答案
您可以这样做:
我想您的按钮位于某个组件中,并且iam使用该组件的名称作为 ComponentName
I suppose your button is in some component and iam using that component's name as ComponentName
import React from 'react';
import { shallow } from 'enzyme';
import ComponentName from './ComponentName'
describe('Test Button component', () => {
it('Test click event', () => {
const component = shallow((<ComponentName />));
button.find('button').simulate('click');
//write an expectation here if suppose you are setting state in your deleteData function you can do like this
component.update();//if you are setting state
expect(component.state().stateVariableName).toEqual(value you are expecting after setState in deleteData);
});
});
编辑:对于普通的函数调用测试,我们可以使用spyOn:
it('calls click event', () => {
const FakeFun = jest.spyOn(ComponentName.prototype, 'deleteData');
const component = shallow((<ComponentName />));
button.find('button').simulate('click');
component.update();
expect(FakeFun).toHaveBeenCalled();
});
这篇关于如何测试一个功能被称为React Jest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文