首页 > 解决方案 > 如何在 Jest 和 Enzyme 中验证 React 道具?

问题描述

所以我试图学习 React 中的测试,我有这个:Button.jsButton.test.js

该问题与以下代码一起注释:

// Button.js
import React from 'react';
import { string, bool, func } from 'prop-types';
import { StyledButton } from './styled'

const Button = ({
  size,
  text,
}) => (
  <StyledButton
    size={size}
    // the test will alway fail with result:
    // Expected value to be: "Join us"
    // Received: undefined
    // Unless I add add this line below
    text={text}
  >
    {text} // but the text props is here. That is my current practice of passing the props to the children, am I missing anything?
  </StyledButton>
);

Button.propTypes = {
  size: string,
  text: string,
};

Button.defaultProps = {
  size: '',
  text: '',
};

export default Button;

// Button.test.js
import React from 'react';
import { shallow } from 'enzyme';

import Button from '../../components/Button/Button';

describe('Component: Button', () => {
  const minProps = {
    text: '',
    size: '',
  };  

  it('renders a button in size of "small" with text in it', () => {
    const wrapper = shallow(
      <Button {...minProps} size="small" text="Join us" />
    );

    expect(wrapper.prop('size')).toBe('small');
    expect(wrapper.prop('text')).toBe('Join us');
  });
});


// StyledButton
import Button from 'antd/lib/button';

const StyledButton = styled(Button)`
  &.ant-btn {
    padding: 0 24px;

    ${({ size }) => {
      if (size === 'small') {
        return css`
          font-size: 14px;
          line-height: 32px;
        `;
      }
      return null;
    }};
`;

export { StyledButton };

有谁知道为什么测试不会通过,除非我将道具传递给StyledButton?

标签: javascriptreactjsunit-testingjestjsenzyme

解决方案


在断言props之前,您需要StyledButton在组件中找到Button

// Button.test.js
import React from 'react';
import { shallow } from 'enzyme';

import Button from '../../components/Button/Button';
import { StyledButton } from './styled'

describe('Component: Button', () => {
  const minProps = {
    text: '',
    size: '',
  };  

  it('renders a button in size of "small" with text in it', () => {
    const wrapper = shallow(
      <Button {...minProps} size="small" text="Join us" />
    );

    expect(wrapper.find(StyledButton).prop('size')).toBe('small');
    expect(wrapper.find(StyledButton).prop('text')).toBe('Join us');
  });
});

推荐阅读