使用 sinon 测试 React PropTypes

Testing React PropTypes with sinon

作为示例,我使用了 Make React PropType warnings throw errors with enzyme.js + sinon.js + mocha.js

我有一个带有一个必需道具的 React 组件:

class Pagination extends Component {
    render() {
        return (
            ... render some stuff
        );
    }
}

Pagination.propTypes = {
    total: PropTypes.number.isRequired
};

这是测试:

describe('(Component) Pagination', () => {
      before(() => {
         sinon.stub(console, 'error', (warning) => { throw new Error(warning) })
      })
      after(() => { console.error.restore() })

      it('render fails without props', () => {
          shallow(<Pagination />);
      });

      it('render fails without props2', () => {
        shallow(<Pagination />);
      });
    });

在 运行 之后测试第一个崩溃,但第二个 - 没有。测试是相似的。 我认为问题在于 React 只抛出一次警告消息。 如何避免这种情况?

我想进行 2 个测试:一个在没有设置 props 时会崩溃,第二个在有 props 的情况下工作正常。

您可以找到解决方法 here:

Pagination.displayName = Math.random().toString();

你显然是对的,这是因为相同的组件,如果你在每次测试之前都这样做,那么它就会欺骗它。只是一个黑客,但它有效。显然没有更好的办法。

P.S。我在 beforeEach 中这样做是为了不自己在每次测试中都编写它。 P.P.S. random 不是最可靠的,因为你可以获得相同的名称并且它会失败,如果它不够好,可以使用 guid 或任何可以使用的东西,这只是一个例子。