使用jest进行React测试历史推送



我正在尝试测试一个菜单栏,它使用history.push处理到某些页面的路由。我正在使用Primreact菜单栏组件。

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/>)
//??
})
})

由于history是组件的道具,因此可以创建一个模拟历史对象并将其传递给组件。为了测试items阵列中的command功能。您需要在测试用例中使用wrapper.state('items')来获取items数组,然后访问并测试command函数。

以下是单元测试解决方案:

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

相关内容

  • 没有找到相关文章