简体   繁体   中英

Unable to test React propType with custom validator

I'm using jest with react-testing-library to test a component that has a custom prop-types validator. The validator looks like this:

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”.`);
    }
},

My test looks like this:

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

The validator works as expected when rendering a faulty aspectRatio . I get the following error in the console:

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

But when running the above test, I get this message in the terminal:

  ● 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 |

What am I missing?

Since the propType validator doesn't actually throw , I was able to resolve by testing for console.warn content.

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”.');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM