简体   繁体   English

如何使用 React-Testing-Library 测试 mapDispatchToProps?

[英]How can I test the mapDispatchToProps with React-Testing-Library?

I have to test the below component:我必须测试以下组件:

import React from 'react';
import { connect } from 'react-redux';

import { open as openModal } from 'redux/actions/ModalActions';
import { MODAL_CONTENT_ADD_TO_ALBUM } from 'constants/ModalNameConstants';

import ContentAddToAlbumModal from 'components/ContentAddToAlbumModal';
import AddSection from 'components/AddSection';

export function AddToAlbumButton(props) {
  const { openUploadModal } = props;

  return (
    <>
      <div>
        <div>
          <AddSection
            onClick={openUploadModal}
          />
        </div>
      </div>
      <ContentAddToAlbumModal/>
    </>
  );
}

function mapDispatchToProps(dispatch, props) {
  return {
    openUploadModal() {
      return dispatch(
        openModal(MODAL_CONTENT_ADD_TO_ALBUM, props.content.get('id'))
      );
    },
  };
}

export default connect(null, mapDispatchToProps)(AddToAlbumButton);

I have written my test case as below:我写了我的测试用例如下:

import React from 'react';
import {render} from '@testing-library/react';
import {AddToAlbumButton} from 'components/AddToAlbumButton';

jest.mock('components/ContentAddToAlbumModal', () => {
  return function ContentAddToAlbumModal() {
      return (
      <div>
          ContentAddToAlbumModal
      </div>
      )
  };
});

jest.mock('components/AddSection', () => {
  return function AddSection({openUploadModal}) {
      return (
      <div onClick={openUploadModal}>
          AddSection
      </div>
      )
  };
});


describe('AddToAlbumButton component', () => {

  const props = {
    openUploadModal: jest.fn()
  };

  it('Should render snapshot of AddToAlbumButton component correctly', () => {
    const {asFragment} = render(<AddToAlbumButton {...props} />);    
    expect(asFragment()).toMatchSnapshot();
  })
});

I want to test my mapDispatchToProps function too, how could I test it without exporting it publicly.我也想测试我的 mapDispatchToProps function ,我怎么能在不公开导出它的情况下测试它。 And how should I test the connected component?我应该如何测试连接的组件?

I was looking over the inte.net for suggestions.我在 inte.net 上寻找建议。 One I found is to mock the 'react-redux' module by creating a file in mocks folder of jest directory with the code snippet as:我发现的一个是通过在 jest 目录的mocks文件夹中创建一个文件来模拟“react-redux”模块,代码片段如下:

const mockDispatch = jest.fn(action => action);
module.exports = {
    connect: (mapStateToProps, mapDispatchToProps) => reactComponent => ({
        mapStateToProps,
        mapDispatchToProps: (dispatch = mockDispatch, ownProps) => (
            mapDispatchToProps(dispatch, ownProps)
        ),
        [reactComponent.displayName || reactComponent.name || 'reactComponent']: reactComponent,
        mockDispatch,
    }),
    Provider: ({ children }) => children,
};

How should I use this above code snippet with 'React Testing Library'.我应该如何将上面的代码片段与“反应测试库”一起使用。 What's missing from my test case?我的测试用例中缺少什么? How should I proceed?我该如何进行?

Thanks谢谢

You can use redux-mock-store package to create a mocked store.您可以使用redux-mock-store package 创建模拟商店。 Wrap your component with Provider with this mocked store.使用这个模拟商店用Provider包装你的组件。

You can get all the actions by calling store.getActions() .您可以通过调用store.getActions()获取所有操作。 Finally, you can use any assertion library to test the payload.最后,您可以使用任何断言库来测试负载。

This testing method is closer to integration testing, integrating React component, connect , and mapDispatchToProps function.这种测试方式更接近于集成测试,集成了React组件、 connectmapDispatchToProps function。

index.tsx : index.tsx

import React from 'react';
import { connect } from 'react-redux';
import { open as openModal } from './actions';
import ContentAddToAlbumModal from './components/ContentAddToAlbumModal';
import AddSection from './components/AddSection';
const MODAL_CONTENT_ADD_TO_ALBUM = 'MODAL_CONTENT_ADD_TO_ALBUM';

export function AddToAlbumButton(props) {
  return (
    <>
      <AddSection onClick={props.openUploadModal} />
      <ContentAddToAlbumModal />
    </>
  );
}

function mapDispatchToProps(dispatch, props) {
  return {
    openUploadModal() {
      return dispatch(openModal(MODAL_CONTENT_ADD_TO_ALBUM, props.content.get('id')));
    },
  };
}

export default connect(null, mapDispatchToProps)(AddToAlbumButton);

components/ContentAddToAlbumModal.tsx : components/ContentAddToAlbumModal.tsx

import React from 'react';

export default function ContentAddToAlbumModal() {
  return <div>real ContentAddToAlbumModal</div>;
}

components/AddSection.tsx : components/AddSection.tsx

import React from 'react';

export default function AddSection({ onClick }) {
  return <div onClick={onClick}>real AddSection</div>;
}

actions.ts : actions.ts

export function open(type, id) {
  return { type, payload: { id } };
}

index.test.tsx : index.test.tsx

import { render, fireEvent, screen } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux';
import createMockStore from 'redux-mock-store';
import AddToAlbumButton from './';

const mockStore = createMockStore();

jest.mock('./components/ContentAddToAlbumModal', () => {
  return function ContentAddToAlbumModal() {
    return <div>ContentAddToAlbumModal</div>;
  };
});

jest.mock('./components/AddSection', () => {
  return function AddSection({ onClick }) {
    return <div onClick={onClick}>AddSection</div>;
  };
});

describe('AddToAlbumButton', () => {
  test('should pass', () => {
    const store = mockStore({});
    const content = {
      get(key) {
        return '123';
      },
    };
    render(
      <Provider store={store}>
        <AddToAlbumButton content={content} />
      </Provider>
    );
    fireEvent.click(screen.getByText(/AddSection/));
    expect(store.getActions()).toEqual([{ type: 'MODAL_CONTENT_ADD_TO_ALBUM', payload: { id: '123' } }]);
  });
});

test result:测试结果:

 PASS  examples/69525117/index.test.tsx (8.636 s)
  AddToAlbumButton
    ✓ should pass (35 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
 actions.ts |     100 |      100 |     100 |     100 |                   
 index.tsx  |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.788 s, estimated 10 s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何测试与 Jest/react-testing-library 反应的上下文 - How can I test a context in react with Jest/react-testing-library 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何使用 react-testing-library 测试 React 组件的 css 属性? - How can I test css properties for a React component using react-testing-library? 如何使用jest和react-testing-library测试上下文提供的功能? - How can I test functions that are provided by context using jest and react-testing-library? 如何使用 jest 和 react-testing-library 测试来自 sass 的 styles? - How can I test styles coming from sass with jest and react-testing-library? 如何使用 Jest 和 react-testing-library 测试 react-dropzone? - How to test react-dropzone with Jest and react-testing-library? 如何使用 react-testing-library 测试 react-select - how to test react-select with react-testing-library 如何用 jest 和 react-testing-library 测试 react-toastify - How to test react-toastify with jest and react-testing-library 如何在react-testing-library中测试React Router路由参数? - How would I test for a react router route param in react-testing-library? 如何在反应测试库中测试父子关系? - How to test parent child relationship in react-testing-library?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM