DEV Community

Cover image for Testing and Modules
Sarah Hudaib
Sarah Hudaib

Posted on

Testing and Modules

What are Unit tests and TDD?

Unit tests:

Unit tests are some pieces of code that exercise the input, the output, and the behavior of your code.

TDD tests:

Test-Driven Development is a strategy that entails first thinking about (and writing!) tests.

Baby Steps:

  1. what is the smaller test that we can do against a function?
  def test_should_return_female_when_the_name_is_from_female_gender():
    detector = GenderDetector()
    expected_gender = detector.run(Ana)
    assert expected_gender == female
Enter fullscreen mode Exit fullscreen mode
  1. There are some details to pay attention. The first one is the test name. The tests can be considered as your live documentation.

  2. The test file name should follow the same name as the module name.

  3. It’s ideal to separate the tests folder from the production code (the implementation)

  4. Another thing to care about is the structure. A convention widely used is the AAA: Arrange, Act and Assert.

  • Arrange: you need to organize the data needed to execute that piece of code (input)

  • Act: here you will execute the code being tested (exercise the behaviour)

  • Assert: after executing the code, you will check if the result (output) is the same as you were expecting

The Cycle:

The cycle is made by three steps:

  • 🆘 Write a unit test and make it fail (it needs to fail because the feature isn’t there, right? If this test passes, call the Ghostwriters, really)

  • ✅ Write the feature and make the test pass! (you can dance after that)

  • 🔵 Refactor the code — the first version doesn’t need to be the beautiful one (don’t be shy)

Takeaways

To remember:

  • The greatest advantage of TDD is to craft the software design first.

  • Your code will be more reliable: after a change, you can run your tests and be in peace.

  • The beginning may be hard — and that’s fine. You just need to practice!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay