Yago Marinho
Back to the articles
  • NodeJS
  • Jest

Implementing Tests with Jest: Making Sure the Code Is Reliable

I adopted Jest to test my code and gained a lot in confidence and quality. That journey made me see the real value of TDD in day-to-day work.

Photo of Yago MarinhoBy: Yago MarinhoLast updated on:
You can find the project's full code on GitHub through this link: click here

I was browsing some tech and industry discussions on Reddit when I came across this question from a user: “How widely is TDD (Test Driven Development) actually used in the industry?”. The answer was as good as the question: “the term (TDD) has been so watered down that today people use it as in 'You tested it?! Then it's TDD!', when it really isn't.”
That exchange got me thinking. In the code I've been writing, the practice isn't TDD — and the reason is simple: I wrote the application first and only then created the tests. If the approach is literally called “test-driven development”, it makes no sense to say I'm doing TDD when the flow went the other way around.
But, naming aside, the central point is something else: tests are indispensable. They keep the code reliable as the project grows, and without them every bit of maintenance or every fix turns into a blind hunt for possible bugs.

Table of contents

Why does writing tests matter?

Tests aren't an “extra” we tack on at the end of a project. They're a fundamental part of the development cycle because they let the code evolve safely. When there's test coverage, you can refactor without fear of breaking something that was already working.
Another important point is that, as the application grows, so does its complexity. Finding a bug without tests gets more and more expensive. With tests, any change can be validated quickly and predictably. In short:
  • They make the system more reliable.
  • They make maintenance easier and less risky.
  • They allow safe refactoring without the feeling of “walking in the dark”.

Why did I choose Jest?

To implement the tests, I chose Jest. The decision was simple: besides being widely used in the JavaScript/TypeScript community, Jest is robust and comes with features that make day-to-day work easier.
A few points that weighed in the choice:
  • Readable results in multiple formats, which make failures quick to understand.
  • Caching of test results, which speeds things up a lot as the suite grows.
  • Built-in mocks and spies, which make it simple to isolate dependencies.
  • Minimal configuration, working well from the start without much setup.
Of course, I could write tests in plain Node.js, but Jest speeds up the implementation, makes the reports clearer and adapts easily to different scenarios in the project.

A practical example

You can find the project's full code on GitHub through this link: click here

One of Jest's biggest advantages is precisely its ability to adapt to existing code. I didn't have to rewrite functions or refactor the whole application just to start testing — all it took was writing tests on top of what was already there.
Look at how Jest adapts to what already exists and makes mocks and reports easy, in the code below:
// __tests__/get-post-list.spec.ts // - uses @notionhq/client with a Client({ auth }) // - queries data_source_id "collection-123" // - applies the filter { published: true } when NODE_ENV === 'production' // - sorts by updated_at desc // - normalizes the results, skipping trashed pages, objects that aren't "page" and pages without the minimum props import { Client } from '@notionhq/client' import { getPostList } from '../src/services/get.posts.list' import { createPage } from './fakes/page.ts' // --- Mock of the external library (@notionhq/client) jest.mock('@notionhq/client', () => { const mockQuery = jest.fn() const MockClient = jest.fn().mockImplementation(() => ({ dataSources: { query: mockQuery, }, })) // exposes the mock so the test can use it ;(MockClient as any).__mockQuery = mockQuery return { Client: MockClient } }) describe('get post list', () => { const mockQuery = (Client as any).__mockQuery as jest.Mock const OLD_ENV = process.env beforeEach(() => { jest.clearAllMocks() jest.useFakeTimers().setSystemTime(new Date('2025-01-01T12:00:00Z')) process.env = { ...OLD_ENV, NOTION_TOKEN: 'test-token' } }) afterAll(() => { process.env = OLD_ENV jest.useRealTimers() }) it('uses the published=true filter in production', async () => { // forces the production environment to check the filter process.env.NODE_ENV = 'production' const results = [ createPage({}), // valid createPage({ id: 'trash', in_trash: true }), // must be skipped createPage({ id: 'not-page', object: 'database' }), // must be skipped createPage({ id: 'missing-props', withProps: false }), // must be skipped // another valid one, with empty props that the normalization handles: createPage({ id: 'empty-props', slug: '', title: '', description: '', withProps: true, }), ] mockQuery.mockResolvedValueOnce({ results }) const list = await getPostList() // 1) the Client was created with the expected token expect(Client).toHaveBeenCalledWith({ auth: 'test-token' }) // 2) the query used the right parameters in production expect(mockQuery).toHaveBeenCalledWith({ data_source_id: 'collection-123', filter: { property: 'published', checkbox: { equals: true }, }, sorts: [{ property: 'updated_at', direction: 'descending' }], page_size: 10, }) // 3) the final list has only the valid, normalized items expect(list).toHaveLength(2) expect(list[0]).toEqual({ slug: 'my-slug', title: 'My Title', description: 'My Description', created_at: expect.any(Date), updated_at: expect.any(Date), }) expect(list[1]).toEqual({ slug: '', title: '', description: '', created_at: expect.any(Date), updated_at: expect.any(Date), }) }) })
This pattern gives me full control over the library's responses without actually connecting to the Notion API. That way, I can check how my code behaves in different scenarios — success, errors, exceptions — just by tweaking the mock.
On top of that, Jest's assertions make checking the expected results very clear (toBe, toEqual, toHaveBeenCalledWith, etc.), and the run reports show precisely which tests passed, which failed and even the project's overall coverage.
In the end, this is what I like most: with just a few lines, I can simulate an entire environment and be confident my code will behave as expected in production.
Besides this one, there are several other tests in the application — all following a similar approach: create mocks, simulate scenarios and check the expected behavior. The whole idea is not having to refactor the code for now, taking advantage of how well Jest fits into the existing flow.

Evolving the mindset

Today, my approach is simple: I write the code and then I create the tests. That already brings immediate reliability benefits and greatly reduces the risk of regressions.
But the point is that, now that the tests exist, it's easier to flip the process: change the test first and only then the code. That shift in perspective paves the way for TDD, where every feature is born from a test that defines the expected behavior.
It's not about flipping a switch overnight, but about a natural evolution. Little by little, this practice changes how we think about implementation: instead of just making sure something works, we start designing the code from how it will be used and validated.

Roadmap and next steps

  • Expand automated tests to other areas of the project.
  • Improve the design to reflect a more modern and consistent blog.
  • Add performance monitoring scripts for the content.
  • Use a bundler to optimize the application's size within the monorepo.
  • Refactor the code to decouple modules and prepare the application for future replacements without major impact.

Conclusion

Implementing tests isn't just about increasing code coverage. It's about building a reliable foundation that lets the project evolve without fear of breaking what already exists.
Jest came in as a practical and robust tool that let me validate behavior, mock external dependencies and gain clarity with simple reports and assertions.
More than that, these tests already open the door to a change in mindset: little by little, the flow can move from writing the code first to designing the expected behavior through tests. That's the natural step toward TDD.
The central point is that, regardless of the approach, quality can't be optional. Testing is part of development — and that's exactly what ensures the project's reliability, scalability and safe evolution.
Photo of Yago Marinho
Yago MarinhoSenior Software Engineer. I build AI-powered products, from design to deploy.
See portfolio ↗