Bye bye Fullstackopen Part 4

Today, I finally completed part 4 in fullstackopen. This took me a while! I had to create a basic blogging API with JWT authentication. A lot of time was spent in structuring this code and writing the tests. The tests were especially tricky because they were integration tests involving JWT authentication, which was something I am not very familiar with.

My biggest blocker for writing the tests was handling the testing of protected resources, like blogs. I wasn't sure how to populate the database with blog posts for testing since blog posts need a user, and I didn't know how to connect the two.

But eventually after trying for a while, I ended up with some messy code that seems to work:

// Populates test database with blogs & users beforeAll(async () => { await startDb() await BlogModel.deleteMany({}) await UserModel.deleteMany({}) const userAuth: UserType = { username: 'test username', password: 'test password', name: 'test name' } const userAuth2: UserType = { username: 'test username 2', password: 'test password 2', name: 'test name 2' } const userJson = (await api.post('/api/auth/signup').send(userAuth)).body const token = (await api.post('/api/auth/login').send(userAuth)).body.token const userJson2 = (await api.post('/api/auth/signup').send(userAuth2)).body const token2 = (await api.post('/api/auth/login').send(userAuth2)).body.token auth.token = token auth.userId = userJson.id auth2.token = token2 const user = await UserService.getById(userJson.id) const blogDocuments = data.map(blog => { blog.user = userJson.id return new BlogModel(blog) }) blogDocuments.map(blog => { user!.blogs = user?.blogs?.concat(blog._id as mongoose.Schema.Types.ObjectId) }) await BlogModel.bulkSave(blogDocuments) await user!.save() })

After that, I was able to write tests that checked things like whether or not unauthorized users could view other peoples blogs. Writing some of tests also resulted in me finding some bugs with my code which I would've missed otherwise. This really made me realize the value of writing these tests!

Here is my source code for my blog API code: repo