无法使用自定义验证器测试 React propType

Unable to test React propType with custom validator

我正在使用带有 react-testing-library 的 jest 来测试具有自定义 prop-types 验证器的组件。验证器看起来像这样:

aspectRatio: (props, propName, componentName) => {
    const value = props[propName];
    const cleaned = value
        .trim()
        .replace(/[^0-9:]+/g, ''); // Replace everything but numbers and forward slash.

    // Ensure value is “number/number”.
    const isCorrectFormat = /^\d+:\d+$/.test(cleaned);

    if (!isCorrectFormat) {
        return new Error(`Invalid value format “${value}” supplied to “${propName}” prop in “${componentName}” component. Expected something like “3:2”.`);
    }
},

我的测试是这样的:

test('throws error when incorrect aspect ratio format passed', () => {
    expect(() => {
        render(
            <Picture
                alt="Hello, picture."
                aspectRatio="1-1/8"
                src="test/books.jpg"
            />,
        );
    }).toThrowError();
});

验证器在呈现错误 aspectRatio 时按预期工作。我在控制台中收到以下错误:

Warning: Failed prop type: Invalid value format “1-1/8” supplied to “aspectRatio” prop in “Picture” component. Expected something like “3:2”.

但是当 运行 以上测试时,我在终端中收到此消息:

  ● throws error when incorrect aspect ratio format passed

    expect(received).toThrowError()

    Received function did not throw

      81 |          />,
      82 |      );
    > 83 |  }).toThrowError();
         |     ^
      84 |  spy.mockRestore();
      85 | });
      86 |

我错过了什么?

由于道具类型验证实际上并没有 throw,我能够通过测试 console.warn 内容来解决。

test('throws error when incorrect aspect ratio format passed', () => {
    console.error = jest.fn();
    render(
        <Picture
            alt="Hello, picture."
            aspectRatio="1-1/8"
            src="test/books.jpg"
        />,
    );
    expect(console.error.mock.calls[0][2]).toBe('Invalid value format “1-1/8” supplied to “aspectRatio” prop in “Picture” component. Expected something like “3:2”.');
});