Current section: Test Structure 6 exercises

Implement a Declarative API


00:00 Let's start from taking the API we want and just copy it for reference. So we can see that expect is a function, and let's declare it like that. Function expect, it accepts one argument which is the actual value of the type unknown, because we don't know what the test is going to pass here. And to have this nice little chaining of to be, it has to return an object

00:19 that has a key to be, which is a function. That function accepts the expected value, which is also the type unknown. And inside does the same comparison that we did here with our manual approach. So I'm just going to copy it here and compare the actual value to expected.

00:39 And then we want to adjust the error message to include both of these. Let's just copy a nice little placeholder from here. So this error. This is a very basic expect function that accepts the actual result, returns an object to have this to be chaining, and then the expected result, and does the comparison.

00:59 If those are not the same, we will throw a meaningful error message to let us know. As the next step, let's refactor the existing tests. So for John, let's just use expect greetJohn to be helloJohn. And for Sarah, we will actually drop this need to have the additional message variable,

01:17 because now the actual result will be encapsulated in the expect call. So I'll drop this, and I will wrap this in the expect call. To be congratsSarah. Notice how smaller and more readable our assertions became. But first, let's try to run them. Let's open a terminal and run the test.

01:36 We can see that the test is passing. The whole point of doing this exercise and introducing this expect function is to have a more declarative API, which is more readable, but also more manageable. So in the future, when we will be comparing different data structures, not just strings, we can introduce different methods in addition to this to be method,

01:53 like to equal, to throw, or maybe to be truthy, to help us with writing better tests.