Реагируйте на историю испытаний pu sh, используя шутку - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь проверить строку меню, которая обрабатывает маршрутизацию к некоторым страницам, используя history.push. Я использую компонент Primereact Menubar .

 class MenubarComponent extends React.Component {

    constructor() {
        super();
        this.state = {
            items: [
                {
                    label: "Home",
                    icon: "pi pi-home",
                    command: () => (this.props.history.push("/"))
                },
                {
                    label: "About",
                    icon: "pi pi-info",
                    command: () => (this.props.history.push("/about"))
                }
            ]
        }
    }

    render() {
        return (
            <Menubar model={this.state.items}/>
        )
    }
}

export default withRouter(MenubarComponent)

Как я могу убедиться, что при нажатии кнопки меню, она переходит на нужную страницу?

     describe('MenubarComponent', () => {
        it('should navigate on menuitem click', () => {
            const menubarItemsMock = jest.fn();
            const item = {
              label: "Home",
              icon: "pi pi-home",
              command: () => (this.props.history.push("/"))
           }
            const wrapper = shallow(<MenubarComponent/>)
            //??
        })
    })

1 Ответ

1 голос
/ 29 апреля 2020

Вот решение для модульного тестирования:

menubarComponent.jsx:

import React from 'react';
import { withRouter } from 'react-router-dom';
import Menubar from './menubar';

class MenubarComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        {
          label: 'Home',
          icon: 'pi pi-home',
          command: () => this.props.history.push('/'),
        },
        {
          label: 'About',
          icon: 'pi pi-info',
          command: () => this.props.history.push('/about'),
        },
      ],
    };
  }

  render() {
    return <Menubar model={this.state.items} />;
  }
}

export default withRouter(MenubarComponent);

menubar.jsx:

import React from 'react';

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

menubarComponent.test.jsx:

import MenubarComponent from './menubarComponent';
import { shallow } from 'enzyme';
import React from 'react';

describe('61476449', () => {
  it('should pass', () => {
    const mProps = { history: { push: jest.fn() } };
    const wrapper = shallow(<MenubarComponent.WrappedComponent {...mProps}></MenubarComponent.WrappedComponent>);
    const items = wrapper.state('items');
    items[0].command();
    expect(mProps.history.push).toBeCalledWith('/');
    items[1].command();
    expect(mProps.history.push).toBeCalledWith('/about');
  });
});

Результаты модульных испытаний с отчетом о покрытии:

 PASS  stackoverflow/61476449/menubarComponent.test.jsx (8.848s)
  61476449
    ✓ should pass (7ms)

----------------------|---------|----------|---------|---------|-------------------
File                  | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------------|---------|----------|---------|---------|-------------------
All files             |   93.75 |      100 |   83.33 |   93.33 |                   
 menubar.jsx          |   66.67 |      100 |       0 |   66.67 | 4                 
 menubarComponent.jsx |     100 |      100 |     100 |     100 |                   
----------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.886s, estimated 10s
...