Reactjs React Redux连接组件与异步操作测试

Reactjs React Redux连接组件与异步操作测试,reactjs,react-redux,jestjs,react-testing-library,connected-components,Reactjs,React Redux,Jestjs,React Testing Library,Connected Components,我在React-Redux连接组件测试中遇到问题。我想用异步操作测试这个组件,但在控制台中,我总是得到一个错误。。。我使用带有jest的React测试库进行测试(不是酶) 有一个控制台错误 expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: [Function anonymous] Received: [Function anonymous] Number of calls: 1 45 | it('should

我在React-Redux连接组件测试中遇到问题。我想用异步操作测试这个组件,但在控制台中,我总是得到一个错误。。。我使用带有jest的React测试库进行测试(不是酶)

有一个控制台错误

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: [Function anonymous]
Received: [Function anonymous]

Number of calls: 1

  45 |   it('should dispatch an action on page first render', () => {
  46 |     expect(store.dispatch).toHaveBeenCalledTimes(1);
> 47 |     expect(store.dispatch).toHaveBeenCalledWith(fetchTop10());
     |                            ^
  48 |   });
  49 | });
  50 |<br /><br />
expect(jest.fn())。toHaveBeenCalledWith(…expected)
预期:[函数匿名]
已收到:[匿名函数]
电话号码:1
45 |它('应该在页面第一次呈现时发送操作',()=>{
46 |预计(储存、发货)已被催收时间(1);
>47 |期望(store.dispatch).toHaveBeenCalledWith(fetchTop10());
|                            ^
48 |   });
49 | });
50 |

存在已连接的组件“CardList.js”

import React,{Fragment,useffect}来自'React';
从“道具类型”导入道具类型;
从'react router dom'导入{Link};
//重演
从'react redux'导入{connect};
//行动
从“../../actions/fetchTitles”;/”导入{fetchTop10}带有数据响应的异步api调用
//乌提尔斯
从“/CardItem”导入CardItem;
const CardList=({fetchTop10,top10})=>{
useffect(()=>{
(异步()=>{
等待fetchTop10();
})();
},[fetchTop10]);
const renderCards=()=>{
如果(top10.length==0){//这是用于代替微调器的权杖
return[1,2,3,4,5,6,7,8,9,10]。map((el)=>{
返回;
});
}
返回top10.map((title)=>{//来自ActionAPI调用的实际数据
返回;
});
};
返回(
每周最佳选手
{renderCards()}
查看更多&rarr;
);
};
CardList.propTypes={
fetchTop10:PropTypes.func.isRequired,
top10:PropTypes.array.isRequired,
};
常量mapStateToProps=(状态)=>{
返回{top10:state.top10};
};
导出默认连接(MapStateTops,{fetchTop10})(CardList)

测试“CardList.test.js”

从'@testing library/react'导入{render,cleanup};
导入“@测试库/jest dom”;
导入“@testinglibrary/jest-dom/extend-expect”;
从“React”导入React;
从'react redux'导入{Provider};
从“react Router dom”导入{Router};//所有项目组件都位于全局路由器中
从“redux thunk”导入thunk;
从“redux模拟存储”导入configureStore;//对于提供商存储
//组成部分
从“../CardList”导入卡片列表;
//物体
从“../../utils/UserTitleObjects”;/”导入{fakeTitle,fakeTitle2}仅包含数据的对象
从“../../../history”导入历史记录;
从“../../../actions/fetchTitles”;/”导入{fetchTop10}带API调用的操作
const mockStore=configureStore([thunk]);
描述('My Connected React Redux Component',()=>{
让存储,组件;
在每个之前(()=>{
商店=模拟商店({
top10:[],
});
store.dispatch=jest.fn();
组件=渲染(
);
});
每次之后(清理);
它('应使用Redux存储中的给定状态进行渲染',()=>{
expect(component.baseElement.querySelectorAll('.scelection').length).toBe(
60
);
});
它('应在页面第一次呈现时发送操作',()=>{

expect(store.dispatch).tohavencalledtimes(1);//这很好在这种情况下,您必须模拟您的操作,否则,您的操作将返回另一个很难断言的函数

我建议您简单地模仿您的动作模块,如下所示:

CardList.test.js


// ...
const mockStore=configureStore([thunk]);
jest.mock(“../../../actions/fetchTitles”,()=>({
__艾斯莫杜勒:没错,
fetchTop10:jest.fn(),
}));
// ...

你能再帮我一次吗?你能提出一个新问题并在其中提到你的问题吗?
import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
// Redux
import { connect } from 'react-redux';
// Actions
import { fetchTop10 } from '../../actions/fetchTitles';   // async api call with data response
// Utils
import CardItem from './CardItem';

const CardList = ({ fetchTop10, top10 }) => {
  useEffect(() => {
    (async () => {
      await fetchTop10();
    })();
  }, [fetchTop10]);

  const renderCards = () => {
    if (top10.length === 0) {   // This is for sceletion insted of spinner
      return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((el) => {
        return <CardItem key={el} />;
      });
    }

    return top10.map((title) => {   // Actual data from action API call
      return <CardItem key={title.id} title={title} />;
    });
  };

  return (
    <Fragment>
      <section id="section-top" className="section-top">
        <h3 className="section-top__heading">Week Bestlers</h3>
        <div className="top-cards">{renderCards()}</div>
        <Link to="/titles" className="section-top__btn btn-link">
          view more &rarr;
        </Link>
      </section>
    </Fragment>
  );
};

CardList.propTypes = {
  fetchTop10: PropTypes.func.isRequired,
  top10: PropTypes.array.isRequired,
};

const mapStateToProps = (state) => {
  return { top10: state.top10 };
};

export default connect(mapStateToProps, { fetchTop10 })(CardList);<br /><br />
import { render, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';  // All project components are in global Router
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';  // for provider store
// Component
import CardList from '../CardList';
// Objects
import { fakeTitle, fakeTitle2 } from '../../utils/UserTitleObjects'; // Just objects with data
import history from '../../../history';
import { fetchTop10 } from '../../../actions/fetchTitles';    // Action with API call

const mockStore = configureStore([thunk]);

describe('My Connected React-Redux Component', () => {
  let store, component;

  beforeEach(() => {
    store = mockStore({
      top10: [],
    });

    store.dispatch = jest.fn();

    component = render(
      <Provider store={store}>
        <Router history={history}>
          <CardList />
        </Router>
      </Provider>
    );
  });

  afterEach(cleanup);

  it('should render with given state from Redux store', () => {
    expect(component.baseElement.querySelectorAll('.sceletion').length).toBe(
      60
    );
  });

  it('should dispatch an action on page first render', () => {
    expect(store.dispatch).toHaveBeenCalledTimes(1);  // this is good  <--
    expect(store.dispatch).toHaveBeenCalledWith(fetchTop10());    // Here starts a problem
  });
});