Check out a free preview of the full JavaScript Testing Practices and Principles course:
The "Your First Test Solution" Lesson is part of the full, JavaScript Testing Practices and Principles course featured in this preview video. Here's what you'd learn in this lesson:

After walking through the solution to the Your First Test Exercise, Kent provides instructions for the next exercise, which is about writing a simple assertion library.

Get Unlimited Access Now

Transcript from the "Your First Test Solution" Lesson

[00:00:00]
>> Kent C. Dodds: Great so, and that was pretty quick little exercise, but let's work through it here, and please ask me any questions that you have. So we've got this bug in sum and we need to be able to run this script and have it fail because that bug exists.

[00:00:17] So what we're gonna do is I'm gonna say, const result = sum(3, 7), and I want that to equal, we'll say our expected is 10. So that's what I expect it to equal. So here I can just say, if the result is not equal to the expected, then I'll throw a new error that says something like, the result of ${result}, or yeah, is not equal to the expected of ${expected}.

[00:00:55] Okay, so now if I run that, I'm gonna get my error, hooray. And then if I replace this to a +, then it should pass, right? So this is a test. At a fundamental level all that a test is is something that throws an error if there is a problem with your system, if there's a bug.

[00:01:18] And the error message is really important. Right now, this error message is pretty good, we could maybe make it a little bit better. We're gonna see how frameworks can help us improve our error messages in assertion libraries. But yeah, at a fundamental level, that's what a test is.

[00:01:34] We could also add a test for subtract as well, but I think you get the idea. Does anybody have any questions about this?
>> Kent C. Dodds: Nothing, okay, great. So our next one, if you look at 2.todo, you're going to write an assertion library. This imperative code right here, not my favorite.

[00:01:57] It would be great to kinda package that up so I could reuse this over and over again. If I wanted to do this, like for example, here's the end result if we test both of these. I'm doing the same kind of thing twice, so it would be really great if I could package that up into a single assertion.

[00:02:14] And so what I want you to do is create a function that can called with an actual value and it returns an object that has some properties on it. The one property we're using here is toBe. And that is a function that accepts the expected value. And if the actual is not equal to the expected value, then it should throw the error, okay?

[00:02:37] And then re-factor this code to use your fancy name assertion library. And then, sorry, to run it, you'll just do node2.todo.js. And you'll get an error, but yeah, so there's no way to know. But if you can make this error happen with this sort of API, then you're good.