使用浅层包装器模拟点击事件时,此定义未定义

时间:2019-07-31 02:23:25

标签: javascript reactjs jestjs enzyme

我正在尝试模拟click事件并测试访问this.props和this.context的处理程序中的逻辑,但我认为这是未定义的。有人可以帮我做错什么吗

反应成分

export default class NavButton extends Component {
    constructor(props, context) {
        super(props, context);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
        e.preventDefault();
        this.context.router.history.push(this.props.navigateTo);  
    }

    render() {
        const {
            navigationText,
        } = this.props;
        return (
            <div>
                <button className="vx_btn" onClick={this.handleClick}>
                    {navigationText}
                </button>
            </div>
        )
    }

}

测试用例


import React from 'react';
import { shallow } from 'enzyme';
import NavButton from './navButton';

const context = {
  router: {
    history: {
      push: jest.fn()
    }
  }
};
const props = {
  navigateTo: '/navigateTo',
  navigationText: 'Next'
};

describe('#handleClick', () => {
  it('should navigate', async () => {
    const navBtnWrapper = shallow(<NavButton {...props }/>, { context});
    const button = navBtnWrapper.find('button');
    button.simulate('click', { preventDefault() {} });
    expect(context.router.history.push).toBeCalledWith('/navigateTo');
  });
});

测试用例失败,并且在我控制台输出时未定义。

1 个答案:

答案 0 :(得分:0)

尝试进行这些更改。

render() {
     const {
         navigateTo,
         navigationText
     } = this.props;

onClick={() => this.handleClick()}

this.context.router.history.push(this.props.navigateTo)