reactjs - 如何在 Jest 单元测试中设置 Prop

标签 reactjs jestjs enzyme

当我运行我的 jest 单元测试时出现以下错误

Warning: Failed prop type: The prop action is marked as required in Button, but its value is undefined. in Button console.error node_modules/prop-types/checkPropTypes.js:20 Warning: Failed prop type: The prop path is marked as required in Button, but its value is undefined. in Button

我尝试创建一个 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
};

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

最佳答案

这是一个工作示例:

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

关于reactjs - 如何在 Jest 单元测试中设置 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55766433/

相关文章:

reactjs - 使用 Jest + Enzyme 测试放大身份验证

javascript - node-fetch 3.0.0 和 jest 给出 SyntaxError : Cannot use import statement outside a module

reactjs - 作为子组件的浅测试函数

reactjs - 用 enzyme 测试链接

javascript - BrowserRouter 中的链接标签仅更改 URL,但不呈现组件

javascript - 单元测试 React 点击外部组件

unit-testing - 如何测试 ReactDOM.render 和另一个导入函数在 Jest 中被调用?

javascript - 如何使用 React.js 将状态属性传递给构造函数中的子组件?

javascript - 如何使用 CodeIgniter 安装 React Js ..?

reactjs - 使用 props 在 React 中设置初始状态,而不使用 React.createClass