【问题标题】:React, Jest, Enzyme how to pass test App.js with store reduxReact,Jest,Enzyme 如何通过 store redux 测试 App.js
【发布时间】:2018-08-28 15:42:51
【问题描述】:

使用create-react-app 创建了一个简单的应用程序,然后更新了我的 App.js 并添加了 redux/store。

class App extends Component {

  render() {

    return (
      <header className="header">
        <h1>todos</h1>
      </header>
    );
  }
}

function mapStateToProps(state) {
  return {
    data: state.data
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(ActionCreators, dispatch);
}

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

然后尝试使用 Enzyme 和 Jest 在 App.test.js 上测试我的应用程序。

import React from 'react'
import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16';
import App from './App'

Enzyme.configure({ adapter: new Adapter() });

function setup() {
  const props = {
    addTodo: jest.fn()
  }

  const enzymeWrapper = mount(<App {...props} />)

  return {
    props,
    enzymeWrapper
  }
}

describe('components', () => {
  describe('App', () => {
    it('should render self and subcomponents', () => {
      const { enzymeWrapper } = setup()
      expect(enzymeWrapper.find('header')).toBe(true)
    })
  })
})

但抛出错误:不变违规:在“连接(应用)”的上下文或道具中找不到“商店”。要么将根组件包装在 a 中,要么将“store”作为道具显式传递给“Connect(App)”。

有什么想法吗?

【问题讨论】:

    标签: reactjs redux enzyme jestjs


    【解决方案1】:

    发生这种情况是因为您尝试在没有 &lt;Provider&gt; 的情况下测试组件(这通常会使商店对其子组件可用)。

    在这种情况下,我通常会在没有 Redux connect 绑定的情况下测试我的组件。为此,您可以导出App 组件本身:

    export class App extends Component // etc...

    然后使用解构赋值语法将其导入到测试文件中:

    import { App } from './App'

    你可以假设(希望...

    Redux docs 中有更多关于此的信息。

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2019-01-27
      • 2020-11-20
      • 2019-02-03
      • 2020-03-30
      • 2019-01-29
      • 1970-01-01
      • 2019-03-22
      • 2017-02-12
      相关资源
      最近更新 更多