Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何更新儿童道具_Reactjs_Jestjs_Enzyme - Fatal编程技术网

Reactjs 如何更新儿童道具

Reactjs 如何更新儿童道具,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我需要突变反应子组件的道具,接收父函数。 更新包装器的函数后,它会发生更改,但不会影响子组件 //Component export default Component extends React.Component{ clickFunction(){ console.log('Parent's Click fn'); } render(){ return( <div> <Button onClic

我需要突变反应子组件的道具,接收父函数。 更新包装器的函数后,它会发生更改,但不会影响子组件

//Component
export default Component extends React.Component{
   clickFunction(){
      console.log('Parent's Click fn');
   }
   render(){
     return(
         <div>
            <Button onClick={this.clickFunction} data-test-id="button"/>
         </div>
     )
   }
}

// Test

import React from 'react';
import {shallow} from 'enzyme';

const mockClickFunction = jest.fn(() => console.log('Mock Click fn'));

describe('Test Component', () => {
   it('Should mutate child prop', () => {
      const wrapper = shallow(<Component />);
      wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn

      console.log(wrapper.instance().clickFunction) // [Function: bound clickFunction]

      wrapper.instance().clickFunction = mockClickFunction;
      wrapper.update();

      console.log(wrapper.instance().clickFunction) // [Function: mockConstructor]

      wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn but should be Mock Click fn
   })
})
//组件
导出默认组件扩展React.Component{
clickFunction(){
console.log('Parent's Click fn');
}
render(){
返回(
)
}
}
//试验
从“React”导入React;
从“酶”导入{shall};
const mockClickFunction=jest.fn(()=>console.log('Mock clickfn'));
描述('测试组件',()=>{
它('Should mutate child prop',()=>{
常量包装器=浅();
wrapper.find('[data test id=“button”]')。simulate('click')//父项的click fn
console.log(wrapper.instance().clickFunction)/[函数:绑定clickFunction]
wrapper.instance().clickFunction=mockClickFunction;
wrapper.update();
console.log(wrapper.instance().clickFunction)/[Function:mockConstructor]
wrapper.find('[data test id=“button”]')。simulate('click')//父项的click fn,但应为Mock click fn
})
})

如何更改子组件onClick函数?

您到底在测试什么?它将在随后的单击中调用两个单独的函数?最好测试点击的效果(假设它们不同)。对于组件,它将下载图像。但对于测试,我将发送虚拟数据。这就是为什么我需要mock这个函数,我在父状态改变后发现子组件的道具将被更新。wrapper.setState({someState:'newstate'})尝试wrapper.instance().forceUpdate();你到底在测试什么?它将在随后的单击中调用两个单独的函数?最好测试点击的效果(假设它们不同)。对于组件,它将下载图像。但对于测试,我将发送虚拟数据。这就是为什么我需要mock这个函数,我在父状态改变后发现子组件的道具将被更新。wrapper.setState({someState:'newstate'})尝试wrapper.instance().forceUpdate();