【问题标题】:Unable to pass props无法通过道具
【发布时间】:2018-12-28 14:16:58
【问题描述】:

大约 6 个月前,我编写了一个反应站点,并进行了一套 Jest 测试,一切运行良好。我已经基于这个创建了第二个项目,但由于某种原因,当我尝试在基本组件渲染上编写相同的测试时,它们失败了。

我得到的错误是

不变违规:在上下文中找不到“商店”或 “连接(控制栏)”的道具。要么将根组件包装在 <Provider>,或者明确地将“store”作为道具传递给 “连接(控制栏)”。

我做了一些阅读,并且有一些关于类似主题的帖子,这似乎表明 TypeScript/Redux 不能很好地协同工作。但是在我的上一个项目中,它与上面完全相同,并且所有测试都运行良好。所以不确定是否只是我引入了导致这种重大变化的更新版本,但希望有人能指出我做错了什么?

我的组件

interface IControlBarProps {
    includeValidated: boolean, 
    includeValidatedChanged: (includeValidated:boolean) => void,
}

export class ControlBar extends React.Component<IControlBarProps, {}> {
    constructor(props: any) {    
        super(props);                
      }

    public render() { ... }
}

function mapStateToProps(state: IStoreState) {
  return {
    includeValidated: state.trade.includeValidated
  };
}    

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    includeValidatedChanged: (includeValidated:boolean) => {
        dispatch(getIncludeValidatedChangedAction(includeValidated))      
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ControlBar);

我的测试

import ControlBar from '../ControlBar';

describe('Control Bar Component', () => {

  it('should render without throwing an error', () => {
    const wrapper = shallow(<ControlBar includeValidated={true} includeValidatedChanged={() => {return;}} />);
    expect(wrapper.find('div.Control-bar').exists()).toEqual(true);
  })
})

【问题讨论】:

    标签: reactjs typescript jestjs enzyme


    【解决方案1】:

    导入未连接到 Redux 的组件,命名导出,而不是连接的默认导出。

    import { ControlBar } from '../ControlBar';
    

    【讨论】:

      【解决方案2】:

      您导入使用 Redux 包装的 ControlBar 组件(导出默认)。要对 ControlBar 进行单元测试,请尝试

      import { ControlBar } from '../ControlBar';
      

      【讨论】:

      • 非常感谢!对 React 来说相当新,所以不同导出之间的区别不是我所知道的,但它确实有效。你能推荐一个解释不同类型出口的好地方吗?
      • 其实很简单。每个 *.js 文件应该只有一个默认导出。当您导入一些没有大括号的组件/功能时,您基本上会导入标记为默认的组件。否则,当您要导入特定或多个组件时,您应该使用带大括号的导入,即import { ControlBar, ScrollBar } from '../Bars.。它是 JS ES6 特性,而不是 React。
      猜你喜欢
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      相关资源
      最近更新 更多