开玩笑/酶:错误:未捕获[TypeError:无法读取withRouter包装的组件中的属性“查询”的未定义]

时间:2018-12-13 23:25:05

标签: reactjs unit-testing jestjs enzyme

因此,我有一个包装在withRouter中的组件,用于访问this.props.router.query并生成以下错误:

  

console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Uncaught [TypeError: Cannot read property 'query' of undefined]

我该如何解决?我的组件如下:

import { withRouter } from 'next/router';

class Order extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { onToken } = this.props.router.query;

    return (
      .......
    );
  }
}

export default withRouter(Order);

我的Order.test.js组件如下:

import Order, { SINGLE_ORDER_QUERY } from '../components/Order';
import { fakeOrder } from '../lib/testUtils';

const mocks = [
  {
    request: { query: SINGLE_ORDER_QUERY, variables: { id: 'ord123' } },
    result: { data: { order: fakeOrder() } },
  },
];

describe('<Order/>', () => {
  it('renders the order', async () => {
    const wrapper = mount(
      <MockedProvider mocks={mocks}>
        <Order id="ord123" />
      </MockedProvider>
    );
    await wait();
    wrapper.update();
    const order = wrapper.find('div[data-test="order"]');
    expect(toJSON(order)).toMatchSnapshot();
  });
});

1 个答案:

答案 0 :(得分:3)

在单元测试中,路由器包或withRouter没有任何意义,因为我们仅测试组件。

要解决此问题而不是导出包装的组件,您也可以导出单个组件:

import { withRouter } from 'next/router';

export class Order extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { onToken } = this.props.router.query;

    return (
      .......
    );
  }
}

export default withRouter(Order);

并将此实例用于单元测试。

import { Order, SINGLE_ORDER_QUERY } from '../components/Order';
import { fakeOrder } from '../lib/testUtils';

const mocks = [
  {
    request: { query: SINGLE_ORDER_QUERY, variables: { id: 'ord123' } },
    result: { data: { order: fakeOrder() } },
  },
];

describe('<Order/>', () => {
  it('renders the order', async () => {
    const router = {
      query: {
        onToken: 1 // Whatever value you want to provide it
      }
    }
    const wrapper = mount(
      <MockedProvider mocks={mocks}>
        <Order id="ord123" router={router} />
      </MockedProvider>
    );
    await wait();
    wrapper.update();
    const order = wrapper.find('div[data-test="order"]');
    expect(toJSON(order)).toMatchSnapshot();
  });
});