【问题标题】:React-testing-library + Redux: Could not find "store" in the context of "Connect(Currency)"React-testing-library + Redux:在“Connect(Currency)”的上下文中找不到“store”
【发布时间】:2020-07-06 22:02:45
【问题描述】:

我有一个如下所示的组件:

import React, { Component } from 'react';
import connect from 'react-redux/es/connect/connect';
import { FormattedNumber } from 'react-intl';

class Currency extends Component {
  render() {
    const { setting, amount } = this.props;
    const { employee } = setting;
    const { currency = 'USD', currency_symbol } = employee.settings;

    /*eslint-disable react/style-prop-object*/
    const applicable_symbol = currency_symbol || currency;
    return (
      <FormattedNumber
        value={amount}
        style="currency"
        currency={applicable_symbol}
      />
    );
  }
}

function mapStateToProps(state) {
  return state;
}

export default connect(mapStateToProps)(Currency);

这是我的测试:

import '@testing-library/jest-dom';
import React from 'react';
import { render } from '../../../../test-utils';
import Currency from '../../Currency';
import configureMockStore from 'redux-mock-store';
import { Provider } from 'react-redux';


test('renders the price in USD format', () => {
  const mockStore = configureMockStore();
  const store = mockStore({
    setting: {
      employee: { settings: { currency: 'USD', currency_symbol: '$' } }
    }
  });


  const { getByText } = render(
    <Provider store={store}>
      <Currency amount={99.99} />
    </Provider>
  );

  expect(getByText(`$99.99`)).toBeInTheDocument();
});

但由于某种原因,它一直失败:

  ● renders the price in USD format

    Could not find "store" in the context of "Connect(Currency)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Currency) in connect options.

      51 |   });
      52 |
    > 53 |   const { getByText } = render(
         |                         ^
      54 |     <Provider store={store}>
      55 |       <Currency amount={123.12} />
      56 |     </Provider>

我做错了什么?我将它包装在 Provider 中,我在嘲笑商店。没看懂

这会产生同样的错误:

  const Wrapper = ({ children }) => (
    <Provider store={store}>{children}</Provider>
  );
  const { getByText } = render(<Currency amount={123.12} />, {
    wrapper: Wrapper
  });

【问题讨论】:

    标签: reactjs redux react-testing-library


    【解决方案1】:

    我想通了。 Jest 不喜欢我正在导入的 connect。这解决了它

    // import connect from 'react-redux/es/connect/connect';
    import { connect } from 'react-redux';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 2022-08-06
      • 2019-11-27
      • 2017-11-11
      • 2021-10-19
      相关资源
      最近更新 更多