首页 > 解决方案 > 如何在开玩笑的单元测试中设置道具

问题描述

运行我的笑话单元测试时出现以下错误

警告:失败的道具类型:道具action在 中标记为必填Button,但其值为undefined。在 Button console.error node_modules/prop-types/checkPropTypes.js:20 警告:失败的道具类型:道具path在 中标记为必需Button,但其值为undefined。在按钮

我尝试创建一个 const 组件,该组件使用我为道具设置的值创建组件,但它仍然没有删除警告。

UNIT TEST
// describe what we are testing
describe('Button Component', () => {

// make our assertion and what we expect to happen 
 it('should render without throwing an error', () => {
    const component = renderer.create(
        <Button action={''}
        path={'Cancel'} />)
   expect(shallow(<Button />).find('div.container').exists()).toBe(true)
 })
})

BUTTON JSX
function Button(props) {
const { action, path } = props;
  return (
     ......

  );
}

Button.propTypes = {
  action: string.isRequired,
  path: string.isRequired
};

我的测试“通过”。不确定这是否是误报,但我只需要错误消失。另外,如何通过单击按钮验证我传递的道具是否存在?

标签: reactjsjestjsenzyme

解决方案


这是一个工作示例:

index.tsx

import React from 'react';
import PropTypes from 'prop-types';

const Button = props => {
  return <div className="container"></div>;
};

Button.propTypes = {
  action: PropTypes.string.isRequired,
  path: PropTypes.string.isRequired
};

export default Button;

index.spec.tsx

import React from 'react';
import Button from '.';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';

describe('Button', () => {
  it('should render without throwing an error ', () => {
    const component = renderer.create(<Button action={''} path={'Cancel'} />);
    expect(
      shallow(<Button action={''} path={'Cancel'} />)
        .find('div.container')
        .exists()
    ).toBe(true);
  });
});

单元测试结果:

 PASS  src/stackoverflow/55766433/index.spec.tsx (10.749s)
  Button
    ✓ should render without throwing an error  (29ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.895s

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55766433


推荐阅读