返回带有Typescript和Jest的ReactNode的测试函数

时间:2020-09-24 05:14:34

标签: reactjs typescript jestjs

我正在尝试测试返回React.ReactNode类型的函数,如下所示:

export const getComponent = (
  storeParams: StoreParams,
  routeItem: RouteItem,
  Component: React.FunctionComponent<{}> | React.ComponentClass<{}, any>
): React.ReactNode => {
  if (isUnauthorized()) {
    return <Error type="auth" />;
  } else if (needsRedirect()) {
    return <Redirect to="/privacy" />;
  }
  return (
    <React.Fragment>
      <Component />
    </React.Fragment>
  );
};

我正在尝试为此编写单元测试,但不确定如何确认函数返回正确的ReactNode。

这是测试的一个示例:

test('return component', () => {
  const component = routes.find((r) => r.id === 'product');

  if (component) {
    const result = getComponent(
      { authorised: true, privacyAccepted: false },
      component,
      component?.component
    );
    // how do I check the component is correct?
  }
});

我不确定是否可以确认result是我所期望的吗?例如,如何检查函数返回<Redirect />

1 个答案:

答案 0 :(得分:1)

使用enzyme软件包的解决方案。

index.tsx

import React from 'react';
import { Redirect } from 'react-router';

interface StoreParams {}
interface RouteItem {}

function isUnauthorized() {
  return false;
}
function needsRedirect() {
  return true;
}

function Error({ type }) {
  return <div>{type}</div>;
}

export const getComponent = (
  storeParams: StoreParams,
  routeItem: RouteItem,
  Component: React.FunctionComponent<{}> | React.ComponentClass<{}, any>,
): React.ReactNode => {
  if (isUnauthorized()) {
    return <Error type="auth" />;
  } else if (needsRedirect()) {
    return <Redirect to="/privacy" />;
  }
  return (
    <React.Fragment>
      <Component />
    </React.Fragment>
  );
};

index.test.tsx

import { getComponent } from '.';
import React from 'react';
import { shallow } from 'enzyme';
import { Redirect } from 'react-router';

describe('64039945', () => {
  it('should pass', () => {
    const component = {
      component: () => <div></div>,
    };
    const result = getComponent({ authorised: true, privacyAccepted: false }, component, component.component);
    const wrapper = shallow(<div>{result}</div>);
    expect(wrapper.find(Redirect)).toHaveLength(1);
  });
});

单元测试结果:

 PASS  src/stackoverflow/64039945/index.test.tsx
  64039945
    ✓ should pass (18ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    72.73 |       50 |       75 |    72.73 |                   |
 index.tsx |    72.73 |       50 |       75 |    72.73 |          15,24,28 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.588s, estimated 10s
相关问题