BRIEFS logo BRIEFS

Writing "Testable" React Components

04/02/2021 , 2m, 58s

Hey friends this is another answer to that lengthy email from Poeter I'm not sure how to say that but properly sorry but the question is how do you write code that can be easily tested and they go at length to explain, you know, sometimes you write, you know smaller functions and we can test those easier but ultimately like, it doesn't always work that way components typically grow and splitting them up makes it feel harder to maintain and I totally agree with that.

I have a blog post called when to break up a react component.And I typically preferred don't break it up if you can help it avoid breaking up your components unnecessarily so yeah, so I prefer having bigger components but then like okay, so how do I test this it's got a bunch of use effects and whatever else in it and then they also bring up the container or yeah the like the smart and dumb components sort of thing or whatever we landed on for the macular for that but I actually never liked that pattern either.

I didn't think that it was a useful.Mechanism for splitting components up or anything it didn't make any sense to me. I mean, I understood like what the rules were but the rules were stupid. I thought and never got any value out of that, so how do we write react components or just code in general let's easier to test well.

I think that if you're testing from a user's perspective and focusing not on building like running necessarily testable code, but just code that's that's sensible that makes sense like there's you're not breaking things up unnecessarily and you're.Associating things across like that are in the same vertical I guess like yeah just not breaking things up unnecessarily and then you test them from the user's perspective, it really doesn't end up mattering how complicated the code within it is necessarily especially when you're we're talking about unit or integration tests where you're mocking HTTP calls that stuff as long as you have MSW to intercept requests and and mock those out and then occasionally maybe mocking a third.

Party library that's complicated or something from there it's it's just rendered the thing and interact with the thing the way that the user does and then assert on its output. I never really think too much about making my code testable necessarily and maybe that's just the curse of knowledge on me just learn to do that naturally and it's something you develop over time, but it's not really something.

I'm thinking about a whole lot. I guess one thing that I do is I I typically avoid doing side effects in the root level of a module and I always put those in a function and that can help make things a little more testable but in general, I'm not really.

Thinking about it too much. I hope that's sort of helpful bye.