Loading
Current section: HTTP Mocking 5 exercises
solution

Efficient Code Organization with Setup Functions

Loading solution

Transcript

00:00 So I normally put these types of setup file or functions toward the bottom of the file. That's like, it reads like a newspaper article where the most important stuff is at the top. And then as things get more implementation detail specific or just more explicit, that comes down toward the bottom. And the reason they used to do that,

00:19 or maybe some newspaper organizations or article organizations still do this. The reason they would do that is so that the editor could just come in and snip out the whatever part of the article they didn't want and the rest of the article would still make sense. And so that way they could really shorten it without too much trouble. So call this newspaper structure,

00:38 I like to do my setup functions toward the bottom. And then people can dive into the specifics if they need to. Okay, so we're gonna make this function called setup request. And we need to take all of this stuff that we're doing that is the same between these two. In fact, it's exactly the same between these two

00:56 and move it down into this setup request function. So then here we can return the request. Looks like this needs to be async. And let's see what else. Yeah, I think that's it. So then we can say our request

01:13 comes from awaits setup request. And same story over here. And our test should continue pass. Yes, they do. Like I said, this is just like normal JavaScript stuff. Take the thing that you're doing in multiple places and put it into a function then call it from those places.

01:36 But I think it was important enough because there are just varying ideas around how you share code. And this is just one situation where I think that it doesn't make sense to do it any other way. And doing like nest describe blocks and nested before each is and stuff

01:55 gets really complicated when really it's just a function. And then of course we can parameterize this and we will to be able to customize some of this. You don't want to go too far on how customized this can be because then at some point you decide, oh man, I've got to test this thing because it's really complicated.

02:11 And fun fact, that's what React testing library is. So originally it was just a simple function I had in my code base and then decided, hey, this is getting kind of complicated. It'd be nice if I test this and then publish it. So never really necessarily intended on publishing testing library, but here we are. So there you go.

02:31 We just moved some code around. Hooray JavaScript.