如何测试React组件propTypes验证 [英] How to test a React component propTypes validation

查看:71
本文介绍了如何测试React组件propTypes验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为PropTypes.shape单元测试React组件的propTypes验证?

How can I unit test the propTypes validation of a React component for PropTypes.shape?

我的组件propTypes验证:

My component propTypes validation:

MyComponent.propTypes = {
  propA: PropTypes.string.isRequired,
  propB: PropTypes.shape({
    inner1: PropTypes.bool.isRequired,
    inner2: PropTypes.func,
  }).isRequired,
}

我的单元测试:

describe('MyComponent propTypes validation', () => {
  it('validates propA', () => {
    expect(MyComponent.propTypes.propA).toBe(PropTypes.string.isRequired);
  })

  // THIS FAILS. Expected: [Function bound checkType], actual: [Function bound checkType]
  it('validates propB', () => {
    expect(MyComponent.propTypes.propB)
      .toEqual(
        PropTypes.shape({
          inner1: PropTypes.bool.isRequired,
          inner2: PropTypes.func,
        }).isRequired
      );
  })
})

推荐答案

尽管我看不到进行单元测试的目的,但是您可以执行以下操作:

Though I don't see the point of unit-testing this you could do the following:

将形状导出为其他对象

// some-descriptive-name-shape.js
export default {
   inner1: PropTypes.bool.isRequired,
   inner2: PropTypes.func,
}

并对其进行单元测试.

或更通用的方法是使用sinon监视console.error并使用无效的属性进行组件渲染,以查看它是否调用了您的间谍

Or more general approach would be to use sinon to spy on console.error and do component render with invalid properties to see it calls your spy

let consoleError;

beforeEach(() => {
    consoleError = spyOn(console, 'error');
});

afterEach(() => {
    consoleError.restore();
})

it('should warn on empty propB, () => {
   // do shallow render of <MyComponent />
   expect(consoleError.called).toBe(true)
   // etc
})

这篇关于如何测试React组件propTypes验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆