I am really struggling to include proper testing practices into my code and would appreciate any advice on how to get going. I work in web dev so my I am interested in how to properly implement a suite of tests for websites and incorporate into it a CI/CD pipeline.

I find a lot of tutorials teach the most basic types of unit tests, 90% of the time most instructors teach how to write a test to sum two numbers, but when it comes to writing real unit test I find it hard to know what I should be testing. I learnt some cypress and have gotten better at including end-to-end testing because that makes more sense to me, but I still feel I am way short of where I should be.

How can I move forward? Did anyone else find themselves in my situation and find good resources to help them learn? Thx

  • It’s odd that functional testing feels easier to you than unit testing; I find the opposite, and that unit tests force better structure into my code. I write fewer monolithic mega functions and more, smaller, simpler functions that can be unit tested.

    Maybe it would help to approach some code in reverse to how you’d normally write it. Test-first development. You write your functional function, but make it full of stubs you think you’ll need to call - top-down design. Then, write unit tests for those stubs - they can be simple at first, basically pass if they get some expected result, and fail otherwise. Then run your tests and confirm they all fail. Then, one by one, fill in the stubs, every time running your tests and watching as more and more tests pass.

    This approach has a number of benefits:

    • test-first development encourages writing smaller, more easily understood functions
    • test-first development gives you high code coverage, which helps prevent bugs from creeping in during development
    • there’s a definite positive feedback endorphin reward from writing watching more tests pass as you develop, which encourages you to keep tests up to date and running clean

    Test-first is easier in some languages than others, as unit tests are easier in this languages.

    I hope this helps!

    • lmaydev@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      edit-2
      3 months ago

      100% this.

      The majority of the times if you are struggling with unit tests it’s because your code isn’t testable.

      It felt weird at first writing code with tests in mind but, as you say, it makes your code much nicer to consume in the long run.