如何在玩笑单元测试中设置道具

时间:2019-04-19 18:48:50

标签: reactjs jestjs enzyme

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

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

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

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
};

我的测试“通过”。不知道这是否是误报,但我只需要走掉错误即可。另外,如何通过单击按钮来验证通过的道具是否在那里?

1 个答案:

答案 0 :(得分:1)

这是一个有效的示例:

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