Loading
Build a TypeScript Project From Scratch Tutorial (19 exercises)
Lesson

Write Logic to Get Streak

In this lesson, you will write the logic that gets the streak if it already exists.

Resources

The following resources provide more information for this lesson:

  • Vitest: [afterEach](<https://vitest.dev/api/#aftereach>)

Transcript

[0:00] [0: 00] First we write the logic to get the streak if it already exists. Open up index.test.ts. First thing we're going to do is update our import statement. We're going to add afterEeach. Then we're going to come down. After the beforeEach, we're going to add an afterEach.
[0:18] [0: 18] What we're doing here is clearing our mockLocalStorage to ensure that each test is isolated and doesn't have anything left over in localStorage. Next thing we're going to do is jump to the bottom of the file. We're going to paste in some more tests. There's a couple things I want to show. First, we have this test suite which is checking, hey, are you storing it in localStorage?

[0:39] [0: 40] Then we're adding a separate test suite to test a different scenario. In this one, we're actually going to pre-populate the streak inside of our mockLocalStorage. That way, we can make sure that it returns the streak from localStorage if it already exists. CD into streak-counter and run pnpm test. That will run vitest and we'll just make sure that everything's failing as we expect. Cool.

[1:04] [1: 04] We added two new suites, our original two are still passing. Great. Expected not to be . Cool. Let's start working through these. We can close our test file and open up index.ts. The first thing we're going to do is change this to streak so that we can use it. We're going to do _localStorage.setItem.

[1:23] [1: 23] For KEY, we'll just hard code it to string for now and then at the end of our function we're going to return streak. Now if we hit Save, come back up. We'll see now we have three passing tests and only one failing, one more to go. Now, we're going to add a block up here, which I'm pacing in.

[1:42] [1: 42] What we're going to do here is we're going to call getItem and for KEY, will do hard-coded streak for now. If it exists in localStorage, we're going to add this try-catch block, which is going to JSON.parse(streakInLocalStorage || " "). If it exists, it's going to return that if it catches, because of that JSON or whatever, a parsing error, will log that to the console.

[2:07] [2: 08] Now if we save and rerun our tests, we'll see that all four tests are now passing. Nice work.