繁体   English   中英

React-jest-enzyme:测试子组件的回调,该子组件在调用回调之前首先调用另一个函数

[英]React-jest-enzyme: testing callback of child component that calls another function first before calling the callback

我正在测试是否在单击子组件中的按钮后调用了传递给子组件的回调。 我通过使用.simulate('click')函数来模拟react-bootstrap按钮<Button></Button>

问题是我按钮的onClick()函数调用了另一个称为update()函数,并且该函数调用了传递给我的子组件的handleSave回调。 <FormControl/>元素的onKeyPress函数还调用我组件的update函数。 这是我的子组件设置的方式:

    update(event) {              

       //Have to check to see if the key stroke is the enter key or if it comes from the button click.
       if(event.charCode === 13 || event.type === 'react-click'){

       // Have to use this get the ref value because this.refs.input.value doesn't work.
       var input = ReactDOM.findDOMNode(this.refs.input);

       input.value = '';
       this.props.handleSave();
   }
}

render(){

    return( 
       <Form>
         <FormControl type="text" ref="input" onKeyPress={this.update.bind(this)} placeholder="Enter Note" />
         <Button onClick={this.update.bind(this)}>Submit </Button>
       </Form>
    )
}

这就是为什么我的update()函数进行检查以查看是否来自charCode==13 ,这是回车键或按钮单击的charCode的原因,因为两者都保存了<FormControl />

我以这种方式进行测试设置:

describe('Input', () => {

const mockHandleText = jest.fn();
const mockHandleSave = jest.fn();
const props          = {handleSave: mockHandleSave}
let input            = shallow(<Input {...props} />);

   describe('when entering a note', () => {

    beforeEach(() => {
            input.find('Button').simulate('click', {
                charCode: 13
            });
    });


    it('adds the note to state', () => {
        expect(props.handleSave).toHaveBeenCalled();
    });
  });
 });

奇怪的是,我必须将一个对象作为第二个参数传递给.simulate()函数,因为如果我不这样做,则会给我一个错误,提示无法读取未定义的charCode,但是当传递一个对象时,该对象不会甚至不必具有事件属性,它只是说

expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called.

另外,如果我不传递带有某些属性的对象,那么它也会破坏我对元素的onChange函数进行回调的其他测试。 为了简单起见,我将其保留在代码示例中,而只是上传了给我带来麻烦的代码。 我还使用带有和的引导表格。 完整的代码在我的github.github.com/Alebron23上。

酶的浅层方法不会呈现整个DOM树,而只是呈现最浅层。 您将无法使用它找到嵌套的子级。 在浅表文档( https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md )中,他们讨论了如果您需要断言子组件的任何行为,则必须使用除shallow()之外的其他东西。

您的其他选择是使用render()或更可能的方法-因为render()是静态的并且您要测试副作用-完全装入()组件( https://github.com/airbnb/enzyme/blob /master/docs/api/mount.md )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM