The main reason to write tests first (TDD) is that the test becomes the first client/user of that code, or more specific; the first client of that API. If the tests are easy to understand the API is probably good. When I started out with TDD I ended up in situations where I felt like "the tests doesn't let my write the code I want to write, this is stupid!". It was only later I realised that my designs, code and APIs was s*it and I should listen to the tests telling me that. If tests are hard to write, the design is either bad or I'm writing some horrible integration code (filesystem, network, db). The other reason to have a test failing before writing the implementation is to ensure the test is testing what you think it is. For example, making the code just throw an error to "make the test fail" would be missing the point. It's not the test that is failing, it's the implementation that fails the test. I would suggest having the test tell you what went wrong: i.e "Expected a total of: 808, was: 0". Now we can see that we are testing for the case we think we are. In the end it's really about building confidence in the tests.
Ha ha. Your comment reminded me about the phrase "it all boils down to confidence" - the main slogan of AdonisJs which happen to be the framework I'm learning right now. Very good explanation.
When I started unit testing I always felt like I was doing if(true) true; if(false) false; And that made me feel like I was just wasting my time. After a few hundreds lines of tests I definitely felt like I was secure, like the API was secure against myself, my own mistakes. The felling of running npm tests after a major update and knowing that everything is fine (without hours of postman tests) is priceless.
Thanks mpj. I like the introduction to the concepts without the use of a test runner. It demonstrated that one can write test by employing just plain old vanilla JavaScript. Look forward to next Monday!
MPJ, this video is great! Congratulations for splitting the unit tests theory from using test runners. One of the mistakes every newcomer can make when starting doing unit tests is to test the unit's implementation instead of input->output confirmation. When I started I tested every property of a class if it exists and if it is a certain type. One hour later I realized my mistake. I hope you will mention the mocking and stubbing in the next videos and if it is a code smell or not. Good luck :)
You, sir, are a godlike teacher. Explaining concepts instead of showing bland code in a specific framework really makes every second worth watching you. Hope you make it as a full time youtuber. Cheers
Thank you very much MPJ! I'm just approaching unit testing and these videos are very useful to me. Love your "unit explanation way", so it's very easy to understand everything without having over-information. Keep doing it!
Last week I was anticipating that this episode would be a Mocha walkthrough or some other test runner suite. Guess I'll have to wait until next Monday, I hope you don't take Thanksgiving off.
What you meant by every test being a unit, could be seen in the Single Responsibility principle, automated tests are also software, hence, best practices still are tied to them, a single test that tries to test the whole API of a component will be probably harder to maintain, way more fragile, and harder to understand. Also, some of us believe that unit tests can be used as part of the documentation, single tests that tell you exactly what certain functionality of the component does could help you a lot when you are working on code you have never touched before.
I just had an epiphany about unit testing and why it works. I've been working through an all-inclusive programming textbook called 'All of Programming', and in it they lay out the entire process for writing an algorithm from start to finish in great detail in a sort of old-school, traditional, tried and true way. The start is defining a problem, then solving one instance of that problem (without writing any code), then making that solution general enough to solve every instance of the problem that is within your scope, and finally writing the code version of that solution to form the algorithm. Well, unit testing is basically a way of working through the problem to find the solution in parallel to writing the algorithm. It's like combining the two steps without losing the benefits of either. The test is basically solving the problem, and then you write code that satisfies the test. Bonus is that you've automatically got something that verifies things like your old code working with your new code, which you showed in the video. Pretty cool, IMO, and not the way I used to think about TDD. Definitely seems like something I should learn.
Hey MPJ, you should really talk about Ava in your next episode. It's a really awesome and modern concurrent test runner for JavaScript, and I really think that your audience would love an episode about it!
Sorry, Ava is way too much magic, future and thingees to introduce at this point. The purpose of this series is to teach unit testing in the most down to earth and straightforward manner possible.
Fun Fun Function, That makes allot of sense. I noticed in some of the other comments your gonna be using Jest which is also a really awesome framework. I actually agree the Jest is easier for beginners since it has much better documentation.
(Disclaimer: Mildly drunk right now, so excuse any poor grammar)Hello!! I haven’t watched this video yet but I want to say something on your latest video so that you might see this comment. Anyway, just wanted to thank you on your insights and advice through all your videos!! I’ve recently taken on a project that is probably slightly out of my depth and while your videos haven’t completely given me every answer I need, they have definitely helped with how I approach the problems at hand, and have given me things to consider I wouldn’t have otherwise considered, so thank you :D
Haha yeaa recognizable this "archeology" feeling of having to dig up the usecases from code to write tests. This vid def has made me want to try out tdd!
The guy with the sunglasses asks the same questions than me. Hopefully the guy with the hat answers perfectly ;) - Keep doing your videos, it's really good
Great suggestion. We have fantastic options for unit testing frontend today compared to just a couple of years ago, and I don't think many people realise that.
Thanks MPJ! I really hope you hit on Mocha/Chai next week! (I dislike the other test runners) Something I also hope you explain is which parts of the application should be tested and how to deal with code that requires external resources. I always run into a brick wall when I get to database dependent code and no idea how or even if you should test code connected to the UI or that requires user interaction.
Yeah, mocking dependencies is definitely something that we'll be spending a lot of time on. I am sorry to be disappointing you though - we'll probably be using Jest, as it's what the React team pushes, and also has the huge pedagogical benefit of having mocking, expectations and test runner bundled into one.
An item object in the example is a flat standard object, not a first class object. It is much easier to validate a value-object. e.g. if an item would be a class with predefined properties. (name, quantity, price), then you can easily validate it when creating an item. The tests for your order class can then always expect that an item is valid. That way you can focus on validating the order process.
Yes. However, that is fixating on a detail with the example rather than the point I was trying to illustrate, which is that the tests warn you when you are breaking your API contract. Try imagining that this, instead, was a REST service accepting a JSON object instead.
Nice, yes. But even then (nerd-hat-mode) you would scoop the flat objects into item objects and validate input, and then still be able to fail early on errors :-) Also, i'm more server-side (php) programming, but love your videos and learn a lot from them, so no hard feelings. Thanx
Just because there is an “object” doesn’t automatically imply that it needs a class to manage it - unless one subscribes to OO dogma. It’s not uncommon in JS that objects are simply used as hashmaps/dictionaries (though ES2015 actually has a proper Map object (and even Set)). The opening episode “Higher-order functions” of this channel should make it clear where the channel’s loyalties lie. Pure functions are easy to test - methods exist for side effects on their instance either by reading or mutating it so they can only be tested in the presence of an instance and it’s state - and in most cases mutability is a feature of instances when it needs to be something that is handled with diligence. Classes are useful in some cases but they really don’t need to be the default. For example validation on creation can easily be handled by “factory functions” (for example, search online: “JavaScript Factory Functions vs Constructor Functions vs Classes”).
Thanks for that great explanation. Nevertheless I'm missing some important points: In theory there is a difference between _TDD_ and _test first_ ( _TDD_ is a special case of _test first_ ). IMHO your video would have benefit from not mixing these terms. Then: TDD-Cycle has *3* Steps: red/green/ *refactor* . The last one is really important to produce really clean code. Hope you create an episode about that soon.
Hi tpd! Thanks for your feedback. I intentionally tried to avoid both the terms test first and tdd and just show the concepts themselves because whenever I use specific terminology the discussion becomes about the definition rather about what we are trying to acheive. Sorry if I let something slip there. The refactor step gets added later in the series, we cant cram everything about unit testing into one video. :)
Hi MPJ. > _"I intentionally tried to avoid both the terms test first and tdd"_ But you failed... ;o) I see your point but I believe that clear communication is important, especially if you want to teach something. The difference between _test first_ and _TDD_ is somewhat essential. And since it is hard to talk about unit testing while avoiding these terms (as your video proves...) they should be explained.
Yeah, again, sorry. Either way, try to disregard it. It's really not what we're aiming for here. We are not looking to explain the exact defintions of these, we're trying to make people "get" the why and what concept. Definitions aren't particularly important at this point in the learning phase - the same reason we're not getting into the definitions of stubs/mocks/doubles. Don't get me wrong, definitons are great but the perfectly succinct definition "monads is just a monoid in the category of endofunctors" is just not a good place to start out - it's better to start showing some monads, maybe even without even using the word monad, and later introduce the general concept.
14:59 what's the background music called ? Is there a playlist for such happy background music ? It's like 30s, 40s Charlie Chaplin movies background. Thanks for great content anyways. God bless you.
I was going thru Testing related materials, and boom, you released a video about it. Now, let me travel to next monday using my time machine that I wrote the tests for. It should work, right? Cause I made tests for it....Right?
I got into a company that hired me after i graduated. They made me do unit tests for already written programs and it got hard to imagine what to do. More tests pile up and i get blamed for it.
What is not quite clear from the video is how thorough the tests should be. - Should we have a test for missing 'name' property? - Should we have a test to make sure that every single item has 'name' property? - Should we have a test for negative quantity values? We might end up having 50 unit tests for the function that's only 5 lines long. Like, what is the borderline? I would like to see a little comment on this question.
Sorry if it's unclear, I try to explain in the series, but here it is again: We write a test in order to drive behaviour. We don't test code per se, we write a test in order to enforce that the code does what we need it to do. For example, do you want your function to handle negative quantity values, or fail if it gets one? If so, write a test for that, make sure it fails, and then write code to make the test pass. This is the power of the test-driven approach, we only write code if it's required to make a test pass.
How do you go about testing in browser js code? Do you create a test page, including the tests? Tbh there is almost no info on how to write this type of tests.
I'm sure this gets asked way too often, I haven't been able to find it in the comments but.. What editor are you using, that displays the JavaScript errors in-line? It seems very useful!
Hey, would you consider making video about FRONT END LOGGING (or at least make an advice here, in the comments? :) )? Unfortunately, this topic is often completely ignored. I know there are plenty of SaaS solutions... but should we go with one? I guess they don't do the hardest part - actually catching the errors. I was thinking of using some library to catch all errors (but how to catch all uncaught errors in all browsers?!) and send them to backend service and then put in log files. And maybe make some aggregation/deduplication on the way? That way we could put it in the same system as backend ones. By the way - thanks for your amazing videos!
Put down a time if i'm wrong but unit testing is about defining behaviour. I didnt see anything that actually should fail. If im testing say a reciprication function that takes in a fraction, if you give me a 0/4 I had better fail in an expected way or have it documented as undefined behaviour. especially for checked and unchecked function pairs for pre conditions
Sorry for the incoherent thoughts haha I did not see you checking that a function "fails properly". If you have a function, for example, throws some exception when a pre-condition isn't met, then you should check that the function is behaving properly and make sure that you're catching that throw in some test because that is how that function behaves. You ought to be testing all the behaviors your function will produce, including throwing or documenting undefined behavior if the end behavior can't be predicted.
I was just hired as a Jr. Software Dev and I do freelance on the side. I made a decision a month or two ago that for my freelance clients I will always do unit testing and it wont be a negotiable item (if it adds time/cost or not). A programmer friend of mine and my new employer both have said that clients sometimes(read:most times) don't understand or care about the benefits of unit testing and sees the bottomline. Do you think this is a good policy to have, always do unit testing for freelance clients ?
I was thinking about this a few months ago. There is a LOT of quality-related things that you can skimp on in a software project. Unit tests is one, but backups, monitoring, error logging, and code review are other examples. These can all be skipped in order to deliver more things in fewer hours, but instead you're paying in higher risks and (much) larger maintenance costs once the codebase grows older than 6 months of development or so. Often, this is invisible to the client, especially one that doesn't know the benefits of these techniques. I was thinking that whatever is part of the quality package could be made part of the sell - i.e. list all the quality work that your consultancy does, and explain in clear terms what the benefit is to the client in business value, and encourage the client to ask your competitors if they include this in their offerings.
When i started using the TDD pattern i was really bored, and i tought that it was stupid, now i can't write a single line of code without writing a test first, its so hard to develop without something that ensure you that you are writing code for the right reasone and not just becouse you think its right.
Probably not in this series. I'm not convinced of it's usefulness. (Not saying that I'm convinced it's useless either, it's just that no programmer I respect has advocated it to me yet)
Yeah. I'm sorry to find so little press about it, especially in JS. I will mention that leebyron.com/testcheck-js is made by Lee Byron and seems pretty great.
Hi MPJ, really insightful, I am going through the phase of starting TDD. There is one challenge I encountered, may need your or the audiences help on it. So we know that we are performing unit testing on a function. But what happens in the case when there are two independent use-cases in the function. Example one use-case will calculate the sum, the other use-case will retrieve data from the database.These are two independent use-cases which reside in the same function but I want to test them against the function that I have created as a whole. How can this be achieved.
Can you please post some code? It's hard to tell why you simply cannot just write two tests. From your description, it also seems like the function might be doing too much work and should be two functions.
My code would look somewhat like this function getLinks() { let data = await db.link.find({id:"abc"}); let result = a + b; result > 5 ? return data: return NULL; } I want to create a test case to check if my data.length > 0 and then based on the condition result > 5 and then it should test against the data(not concerned with this) that I have retrieved from the DB.
They are passed as function args. Sorry I forgot to add that to the function. Any who I just wen through your dependency injection video and got a much clearer picture on how this can be achieved. Will start implementing that. Thanks :)
(1) Mock your db call, either with manual mocks or a mock function (I'm using a mock function in the example). (2) You want to test the expected behaviour of the code from the perspective of it's api. --- Example (Jest) --- test('getLinks returns data if sum is > 5', () => { db.link.find = Jest.fn(() => 'TEST DATA') expect(getLink(2, 4)).toBe('TEST DATA') }) test('getLinks returns null if sum is
Tape is on the other end of the spectrum. For some interesting opinions regarding the choice of testing tool - search online: “Why I use Tape Instead of Mocha & So Should You”.
Hey mpj, what are your thoughts on injecting dependencies through factories as you usually do on videos VS stubbing the modules returned by the require in nodejs ? (like explained in this so answer stackoverflow.com/a/16308099) I personally think that stubbing the required module is to much magic and it will come back in my ass anytime soon, plus sending dependencies in through factories makes everything explicit
Not a fan personally, and I don't agree dependency injection harms code simplicity - it's specifically targeting code simplicity (I think a lot of people confuse terseness with simplicity which is completely different). The notion that introducing a sophisticated magical tool like proxyquire into your toolchain just to avoid passing dependencies would be a more simple solution is pretty ludicrous. If you're a patron, there is actually a fantastic topic on the Fun Fun Forum about this specific topic here: www.funfunforum.com/t/why-i-dont-like-dependency-injection-in-javascript/2406
Well, one can write tests immediately after finishing each piece of code, it's not like you have to wait a week to do it... it takes exactly the same amount of discipline as writing them first...
ivanhoe011 Maybe that’s true for you, but I submit you may be in the minority in that regard. Writing tests after the fact feels like doing one’s own code reviews. Fine if you are by yourself, and a superhero of some kind.
The main reason to write tests first (TDD) is that the test becomes the first client/user of that code, or more specific; the first client of that API. If the tests are easy to understand the API is probably good. When I started out with TDD I ended up in situations where I felt like "the tests doesn't let my write the code I want to write, this is stupid!". It was only later I realised that my designs, code and APIs was s*it and I should listen to the tests telling me that. If tests are hard to write, the design is either bad or I'm writing some horrible integration code (filesystem, network, db).
The other reason to have a test failing before writing the implementation is to ensure the test is testing what you think it is.
For example, making the code just throw an error to "make the test fail" would be missing the point. It's not the test that is failing, it's the implementation that fails the test. I would suggest having the test tell you what went wrong: i.e "Expected a total of: 808, was: 0". Now we can see that we are testing for the case we think we are. In the end it's really about building confidence in the tests.
What a great comment, thanks!
Daniel Sandberg Seriously; That’s a better summary than most entire books on the subject. Bravo!
Frameworks like Mocha can do a lot of that for you. Remember: programming was born to automate boring tasks... like executing all the tests!
Ha ha. Your comment reminded me about the phrase "it all boils down to confidence" - the main slogan of AdonisJs which happen to be the framework I'm learning right now. Very good explanation.
Well said. To add to that: Jest shows what's received and what's expected :)
The Odin Project once again sent me for your channel. You have a real way with words, extremely helpful as always.
He left the channel though :(
@@hackmaster6109 he is back!
@@hackmaster6109 and now he's back again :)
These 23 minutes felt like just 5. This is done really well and improved my perspective towards unit testing! Can't wait for next episode :)
thanks a ton for your kind words!
When I started unit testing I always felt like I was doing if(true) true; if(false) false; And that made me feel like I was just wasting my time. After a few hundreds lines of tests I definitely felt like I was secure, like the API was secure against myself, my own mistakes. The felling of running npm tests after a major update and knowing that everything is fine (without hours of postman tests) is priceless.
Here from The Odin Project - love your videos and your teaching style! You make it both educational and fun :)
He quit YT, so sad
"Rocket Surgery" - Love it!
first heard it from DHH so I can't take credit, but it is a great term!
Good old DHH!
New band name.
Orthodox-ness is a good one too! :D
This is called a Malaphor, they're super fun, highly recommend looking up some more! malaphors.com/
Thanks mpj. I like the introduction to the concepts without the use of a test runner. It demonstrated that one can write test by employing just plain old vanilla JavaScript. Look forward to next Monday!
MPJ, this video is great! Congratulations for splitting the unit tests theory from using test runners.
One of the mistakes every newcomer can make when starting doing unit tests is to test the unit's implementation instead of input->output confirmation.
When I started I tested every property of a class if it exists and if it is a certain type. One hour later I realized my mistake.
I hope you will mention the mocking and stubbing in the next videos and if it is a code smell or not.
Good luck :)
8:04 is why your video series is so great. Having a blast learning from you, thanks!
this guy is genius, or should I say these guys :D
aw
the guys, precisely
You, sir, are a godlike teacher. Explaining concepts instead of showing bland code in a specific framework really makes every second worth watching you. Hope you make it as a full time youtuber. Cheers
Thank you very much MPJ! I'm just approaching unit testing and these videos are very useful to me. Love your "unit explanation way", so it's very easy to understand everything without having over-information. Keep doing it!
The soup analogy was great, very helpful
I really like the soup example, very thoughtful
MPJ: Multiple Personality Javascript-master.
Loved the new idea of "different people" asking questions and commenting as you explain things.
Last week I was anticipating that this episode would be a Mocha walkthrough or some other test runner suite. Guess I'll have to wait until next Monday, I hope you don't take Thanksgiving off.
Really like your new format MPJ! Looking forward to episode 3 💡
Great show, any other hosts would make this topic way too boring, but not you! :) Thanks a lot.
Thank you so much for saying this, I spend a lot of time on making sure that the content keeps your attention.
You are a genius teacher. Oh my god, I am going to gain so much from this channel I am so glad I found this today 💛
Strong pedagogy! I like the fact that you did not use a test-runner!
I think we have a little editing mistake at 3:37, the sunglasses MPJ repeats himself !
hahaha!
Man this intro song is awesome!
curious about the song name!
What you meant by every test being a unit, could be seen in the Single Responsibility principle, automated tests are also software, hence, best practices still are tied to them, a single test that tries to test the whole API of a component will be probably harder to maintain, way more fragile, and harder to understand. Also, some of us believe that unit tests can be used as part of the documentation, single tests that tell you exactly what certain functionality of the component does could help you a lot when you are working on code you have never touched before.
YESSSS!! I waited for this video all week!!!
me too!
I just had an epiphany about unit testing and why it works. I've been working through an all-inclusive programming textbook called 'All of Programming', and in it they lay out the entire process for writing an algorithm from start to finish in great detail in a sort of old-school, traditional, tried and true way. The start is defining a problem, then solving one instance of that problem (without writing any code), then making that solution general enough to solve every instance of the problem that is within your scope, and finally writing the code version of that solution to form the algorithm.
Well, unit testing is basically a way of working through the problem to find the solution in parallel to writing the algorithm. It's like combining the two steps without losing the benefits of either. The test is basically solving the problem, and then you write code that satisfies the test. Bonus is that you've automatically got something that verifies things like your old code working with your new code, which you showed in the video. Pretty cool, IMO, and not the way I used to think about TDD. Definitely seems like something I should learn.
The soup example is very good. Subscribed.
Hey MPJ, you should really talk about Ava in your next episode. It's a really awesome and modern concurrent test runner for JavaScript, and I really think that your audience would love an episode about it!
Sorry, Ava is way too much magic, future and thingees to introduce at this point. The purpose of this series is to teach unit testing in the most down to earth and straightforward manner possible.
Fun Fun Function, That makes allot of sense. I noticed in some of the other comments your gonna be using Jest which is also a really awesome framework. I actually agree the Jest is easier for beginners since it has much better documentation.
Self-taught JS developer here. Gotta say man, your videos are amazing and help me fill in some of my own skill gaps. Awesome videos!
(Disclaimer: Mildly drunk right now, so excuse any poor grammar)Hello!! I haven’t watched this video yet but I want to say something on your latest video so that you might see this comment. Anyway, just wanted to thank you on your insights and advice through all your videos!! I’ve recently taken on a project that is probably slightly out of my depth and while your videos haven’t completely given me every answer I need, they have definitely helped with how I approach the problems at hand, and have given me things to consider I wouldn’t have otherwise considered, so thank you :D
This videos are gold! Not only how but why! Just Big props for the excelente content
First time I see it that clearly. Thanks a lot! You are very good!
You look like Tony Stark on those glasses, I enjoyed every bit of your tutorial
Describing why write tests first using a cooking example -> Pressing Like button instantly :)
Haha yeaa recognizable this "archeology" feeling of having to dig up the usecases from code to write tests. This vid def has made me want to try out tdd!
glad i'm watching this in the future
Actually this whole intro is awesome!!!!
The guy with the sunglasses asks the same questions than me. Hopefully the guy with the hat answers perfectly ;) - Keep doing your videos, it's really good
Could you please tell what is the plugin (or smth.) you use to get results right down in your text editor?
How do you make those inline errors popout? What editor do you use?
Great video MPJ! Thanks!
Really enjoy your videos.
That beat at 15:08 goes hard!!
I know all about Unit tests, but this video awesome and very interesting 👍
I hope the next episode is about testing different types of react component :)
A good topic down the road would be which testing strategies to use on the front-end. Unit testing only goes so far on the front-end.
Great suggestion. We have fantastic options for unit testing frontend today compared to just a couple of years ago, and I don't think many people realise that.
@7:53 I'm dying right now LMFAO
oh my God, this is very funny hahaha
MPJ, what extension do you intall for that "showing error thing" on your vscode?
ariefrizqon thanks!
@@kristoffergonzaga5531 what about ajax calls?, when I write ajax calls it execute the function inmediately?
Hello from Argentina MpJ,you are really awsome
I like the mono acting. Was a treat to watch.🙂 But this was a great explanation in layman's term on why to write test first. Kudoj @mpj
Aewsome content!! congrats!
love this series so much
aww
Thanks MPJ! I really hope you hit on Mocha/Chai next week! (I dislike the other test runners) Something I also hope you explain is which parts of the application should be tested and how to deal with code that requires external resources. I always run into a brick wall when I get to database dependent code and no idea how or even if you should test code connected to the UI or that requires user interaction.
Yeah, mocking dependencies is definitely something that we'll be spending a lot of time on. I am sorry to be disappointing you though - we'll probably be using Jest, as it's what the React team pushes, and also has the huge pedagogical benefit of having mocking, expectations and test runner bundled into one.
Song:
Jules Gaia -- Glitz at the Ritz
An item object in the example is a flat standard object, not a first class object. It is much easier to validate a value-object. e.g. if an item would be a class with predefined properties. (name, quantity, price), then you can easily validate it when creating an item. The tests for your order class can then always expect that an item is valid. That way you can focus on validating the order process.
Yes. However, that is fixating on a detail with the example rather than the point I was trying to illustrate, which is that the tests warn you when you are breaking your API contract. Try imagining that this, instead, was a REST service accepting a JSON object instead.
Nice, yes. But even then (nerd-hat-mode) you would scoop the flat objects into item objects and validate input, and then still be able to fail early on errors :-) Also, i'm more server-side (php) programming, but love your videos and learn a lot from them, so no hard feelings. Thanx
Just because there is an “object” doesn’t automatically imply that it needs a class to manage it - unless one subscribes to OO dogma. It’s not uncommon in JS that objects are simply used as hashmaps/dictionaries (though ES2015 actually has a proper Map object (and even Set)). The opening episode “Higher-order functions” of this channel should make it clear where the channel’s loyalties lie.
Pure functions are easy to test - methods exist for side effects on their instance either by reading or mutating it so they can only be tested in the presence of an instance and it’s state - and in most cases mutability is a feature of instances when it needs to be something that is handled with diligence.
Classes are useful in some cases but they really don’t need to be the default. For example validation on creation can easily be handled by “factory functions” (for example, search online: “JavaScript Factory Functions vs Constructor Functions vs Classes”).
What VSCode extension shows the error and output out like that
Thanks for that great explanation. Nevertheless I'm missing some important points: In theory there is a difference between _TDD_ and _test first_ ( _TDD_ is a special case of _test first_ ). IMHO your video would have benefit from not mixing these terms. Then: TDD-Cycle has *3* Steps: red/green/ *refactor* . The last one is really important to produce really clean code. Hope you create an episode about that soon.
Hi tpd! Thanks for your feedback. I intentionally tried to avoid both the terms test first and tdd and just show the concepts themselves because whenever I use specific terminology the discussion becomes about the definition rather about what we are trying to acheive. Sorry if I let something slip there. The refactor step gets added later in the series, we cant cram everything about unit testing into one video. :)
Hi MPJ.
> _"I intentionally tried to avoid both the terms test first and tdd"_
But you failed... ;o)
I see your point but I believe that clear communication is important, especially if you want to teach something. The difference between _test first_ and _TDD_ is somewhat essential. And since it is hard to talk about unit testing while avoiding these terms (as your video proves...) they should be explained.
Yeah, again, sorry. Either way, try to disregard it. It's really not what we're aiming for here. We are not looking to explain the exact defintions of these, we're trying to make people "get" the why and what concept. Definitions aren't particularly important at this point in the learning phase - the same reason we're not getting into the definitions of stubs/mocks/doubles. Don't get me wrong, definitons are great but the perfectly succinct definition "monads is just a monoid in the category of endofunctors" is just not a good place to start out - it's better to start showing some monads, maybe even without even using the word monad, and later introduce the general concept.
11:00 "yah - they are getting it"
wish this guy still did videos
14:59 what's the background music called ? Is there a playlist for such happy background music ? It's like 30s, 40s Charlie Chaplin movies background. Thanks for great content anyways. God bless you.
tks u, but i have a question. What is the ide or text editor that you are using so that when the error is thrown?
Thank you sir i got it on you descriptions
I was going thru Testing related materials, and boom, you released a video about it.
Now, let me travel to next monday using my time machine that I wrote the tests for. It should work, right? Cause I made tests for it....Right?
Big Thanks for the fun fun fun
17:59 I didn't get how are you running this ? Please clarify
I got into a company that hired me after i graduated. They made me do unit tests for already written programs and it got hard to imagine what to do. More tests pile up and i get blamed for it.
What is not quite clear from the video is how thorough the tests should be.
- Should we have a test for missing 'name' property?
- Should we have a test to make sure that every single item has 'name' property?
- Should we have a test for negative quantity values?
We might end up having 50 unit tests for the function that's only 5 lines long.
Like, what is the borderline? I would like to see a little comment on this question.
Sorry if it's unclear, I try to explain in the series, but here it is again: We write a test in order to drive behaviour. We don't test code per se, we write a test in order to enforce that the code does what we need it to do. For example, do you want your function to handle negative quantity values, or fail if it gets one? If so, write a test for that, make sure it fails, and then write code to make the test pass. This is the power of the test-driven approach, we only write code if it's required to make a test pass.
Oh, this makes sense. Thanks!
Please, what is the name of the extension that runs your code as you write them?
I'm a year late but it's in the description. Quokka!
@@DrDemolition thanks
How do you go about testing in browser js code? Do you create a test page, including the tests? Tbh there is almost no info on how to write this type of tests.
The Odin Project sent me here on this day
I'm sure this gets asked way too often, I haven't been able to find it in the comments but..
What editor are you using, that displays the JavaScript errors in-line? It seems very useful!
see episode description
Hey, would you consider making video about FRONT END LOGGING (or at least make an advice here, in the comments? :) )?
Unfortunately, this topic is often completely ignored. I know there are plenty of SaaS solutions... but should we go with one? I guess they don't do the hardest part - actually catching the errors. I was thinking of using some library to catch all errors (but how to catch all uncaught errors in all browsers?!) and send them to backend service and then put in log files. And maybe make some aggregation/deduplication on the way? That way we could put it in the same system as backend ones.
By the way - thanks for your amazing videos!
Just use sentry.io, it's amazing
I dont think youve mentioned in the videos or bio, what testing library you are using.
What's that electro swing jam that he plays while he does the fast motion working scenes?
It's Glitz at the Ritz, Jump Jive Roar, and Let's Bounce!
How did you find this song and you bought license for it ?
Put down a time if i'm wrong but unit testing is about defining behaviour. I didnt see anything that actually should fail. If im testing say a reciprication function that takes in a fraction, if you give me a 0/4 I had better fail in an expected way or have it documented as undefined behaviour. especially for checked and unchecked function pairs for pre conditions
I'm sorry, I don't really get your question, can you elaborate?
Sorry for the incoherent thoughts haha
I did not see you checking that a function "fails properly".
If you have a function, for example, throws some exception when a pre-condition isn't met, then you should check that the function is behaving properly and make sure that you're catching that throw in some test because that is how that function behaves.
You ought to be testing all the behaviors your function will produce, including throwing or documenting undefined behavior if the end behavior can't be predicted.
Can we use Switch cases in place of If conditions ?
These are incredibly well made 🫡
Is it just me or is there a bug in the code? Quantity zero is treated as unspecified quantity, so it counts as 1.
I was just hired as a Jr. Software Dev and I do freelance on the side. I made a decision a month or two ago that for my freelance clients I will always do unit testing and it wont be a negotiable item (if it adds time/cost or not).
A programmer friend of mine and my new employer both have said that clients sometimes(read:most times) don't understand or care about the benefits of unit testing and sees the bottomline.
Do you think this is a good policy to have, always do unit testing for freelance clients ?
I was thinking about this a few months ago. There is a LOT of quality-related things that you can skimp on in a software project. Unit tests is one, but backups, monitoring, error logging, and code review are other examples. These can all be skipped in order to deliver more things in fewer hours, but instead you're paying in higher risks and (much) larger maintenance costs once the codebase grows older than 6 months of development or so. Often, this is invisible to the client, especially one that doesn't know the benefits of these techniques. I was thinking that whatever is part of the quality package could be made part of the sell - i.e. list all the quality work that your consultancy does, and explain in clear terms what the benefit is to the client in business value, and encourage the client to ask your competitors if they include this in their offerings.
Wonderful information.
Please sir with addon are you using on visual studio code when you write a function or code its show you the output (left red words) thankyou
quokka.funfunfunction.com
Fun Fun Function Thank you sir You save my ass🤩😍😎
what's the name of that plugin u use which displays live error message in red?
Tameem Zaaiter see episode description
We miss u mpj
When i started using the TDD pattern i was really bored, and i tought that it was stupid, now i can't write a single line of code without writing a test first, its so hard to develop without something that ensure you that you are writing code for the right reasone and not just becouse you think its right.
You going to cover property-based testing at some point?
Probably not in this series. I'm not convinced of it's usefulness. (Not saying that I'm convinced it's useless either, it's just that no programmer I respect has advocated it to me yet)
Yeah. I'm sorry to find so little press about it, especially in JS. I will mention that leebyron.com/testcheck-js is made by Lee Byron and seems pretty great.
What vscode xtension is he using that shows the errors inline?
See episode description
What IDE is being used here to automatically check the tests inline?
See episode description!
Ahh thank you! I missed it first time
Which text editor is that one?
Hi MPJ, really insightful, I am going through the phase of starting TDD. There is one challenge I encountered, may need your or the audiences help on it. So we know that we are performing unit testing on a function. But what happens in the case when there are two independent use-cases in the function. Example one use-case will calculate the sum, the other use-case will retrieve data from the database.These are two independent use-cases which reside in the same function but I want to test them against the function that I have created as a whole. How can this be achieved.
Can you please post some code? It's hard to tell why you simply cannot just write two tests.
From your description, it also seems like the function might be doing too much work and should be two functions.
My code would look somewhat like this
function getLinks() {
let data = await db.link.find({id:"abc"});
let result = a + b;
result > 5 ? return data: return NULL;
}
I want to create a test case to check if my data.length > 0 and then based on the condition result > 5 and then it should test against the data(not concerned with this) that I have retrieved from the DB.
Where does a and b come from?
They are passed as function args. Sorry I forgot to add that to the function. Any who I just wen through your dependency injection video and got a much clearer picture on how this can be achieved. Will start implementing that. Thanks :)
(1) Mock your db call, either with manual mocks or a mock function (I'm using a mock function in the example).
(2) You want to test the expected behaviour of the code from the perspective of it's api.
--- Example (Jest) ---
test('getLinks returns data if sum is > 5', () => {
db.link.find = Jest.fn(() => 'TEST DATA')
expect(getLink(2, 4)).toBe('TEST DATA')
})
test('getLinks returns null if sum is
how are you writing the test what tool is this if it isn't jasmine/mocha
that's plain js
Hey, what IDE are you using please?
VS Code: code.visualstudio.com
I am hoping that you cover using Jest.
yep, thats definitely in the plans
No!!! Use Ava, it's so awesome... (or do both)
Awesome, thanks!
Tape is on the other end of the spectrum. For some interesting opinions regarding the choice of testing tool - search online: “Why I use Tape Instead of Mocha & So Should You”.
Blooper at 3:37 ;)
crap!!
Thanks so much
Triiiiiiiiiiiangulation LMFAO
Definitely use Istanbul too. Nothing a good tool for showing missed code paths.
Hey mpj, what are your thoughts on injecting dependencies through factories as you usually do on videos VS stubbing the modules returned by the require in nodejs ? (like explained in this so answer stackoverflow.com/a/16308099)
I personally think that stubbing the required module is to much magic and it will come back in my ass anytime soon, plus sending dependencies in through factories makes everything explicit
Not a fan personally, and I don't agree dependency injection harms code simplicity - it's specifically targeting code simplicity (I think a lot of people confuse terseness with simplicity which is completely different). The notion that introducing a sophisticated magical tool like proxyquire into your toolchain just to avoid passing dependencies would be a more simple solution is pretty ludicrous.
If you're a patron, there is actually a fantastic topic on the Fun Fun Forum about this specific topic here: www.funfunforum.com/t/why-i-dont-like-dependency-injection-in-javascript/2406
Thanks for taking the time! I'll take a look =]
and what about devtips??
they are released on wednesdays. :)
Dude, what's up with your pen? This is some pen for penspinning?
Yep, google "pen spinning mod"
I shall bestow a new name on thee. 'Split the Coder'. Due to the multiple personalities he has.
Well, one can write tests immediately after finishing each piece of code, it's not like you have to wait a week to do it... it takes exactly the same amount of discipline as writing them first...
ivanhoe011 Maybe that’s true for you, but I submit you may be in the minority in that regard. Writing tests after the fact feels like doing one’s own code reviews. Fine if you are by yourself, and a superhero of some kind.