Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch React propTypes warnings on server?

While rendering React components on server all of the propTypes warning messages are falling to general output or process.stdout. For example, this is visible only in terminal or in general application log:

Warning: Failed propType: Required prop `title` was not specified in `Page`.

Is there any way to catch this warnings and transform them or pipe them into another direction? For instance, I want to separate application log and React (as template engine) log. How can I do it?

like image 457
vtambourine Avatar asked Aug 10 '15 21:08

vtambourine


3 Answers

Like @m01, I wanted to make sure that any react errors (and in fact any js errors) cause my unit tests to fail, but I found a much simpler way to do it. At the top level of your tests, put this:

beforeAll(() => {
  console.error = (error) => {
    throw new Error(error);
  };
});
like image 68
Cam Jackson Avatar answered Sep 21 '22 07:09

Cam Jackson


I needed the same thing, but for a different use case. I wanted to make sure that all my unit tests pass without any React warnings.

I use this in my test utils:

expectNoConsoleErrors: function() {
    var savedErrors;
    beforeEach(function () {
        savedErrors = [];
        spyOn(console, 'error').and.callFake(function () {
            var stack = new Error(_.map(arguments).join(' ')).stack;
            // if you need workarounds for come components, put them here
            savedErrors.push(stack);
        });
    });
    afterEach(function () {
        if (savedErrors.length > 0) {
            fail(savedErrors.join('\n'));
        }
    });
},

Then in describe block I put

myTestUtils.expectNoConsoleErrors()

And it works like a charm.

This is not very clean because it will also catch all other calls to console.error, but I don't want them during test anyway, so this seems ok for me.

Also, when I have some misbehaving component producing unnecessary warnings, like e.g. react-input-autosize I can ignore it using:

            // Workaround for https://github.com/JedWatson/react-select/issues/371
            if (_.contains(stack, 'react-input-autosize')) {
                return;
            }

Btw, note that before v0.14, React was using console.warn instead of console.error to produce these warnings.

like image 45
mik01aj Avatar answered Sep 25 '22 07:09

mik01aj


I tried looking into the React src how they print those output messages, but then I realized that it should only be printing those messages in development mode. If your node/iojs runtime is set to the "production" env, React should not even be doing those checks and that's what you want for a real app running. Those warnings are meant just for devs running locally.

like image 23
Bill D Avatar answered Sep 23 '22 07:09

Bill D