Maintaining distance between Business Logic and Display Logic
So instead of writing a named function, pass it to the event handler. It applies to more than the DOM, though. A plenty of APIs which are discovered in the browser and the Node are designed to events or wait for other types of asynchronous work to complete.
Using Callbacks or Promises with Asynchronous Code
In the above illustration, our refactored fetchResult function runs an AJAX request. It symbolizes that we cannot function and test as everything we expected.
Apart from this, one of the most popular ways to organise asynchronous code is to use Promise API. Fortunately, $.ajax and most other of jQuery’s asynchronous functions has a likely return, so a lot of common use cases are already covered.
Avoid Side Effects
Now it is the time to take arguments and return a value based solely on those arguments. If your function depends on some external state, you have to perform a setup in your tests. You’ll have to trust that any other code being run isn’t modifying that same state. In the same mood, avoid writing functions that alter external state. This prevents the adverse effect on your ability to test other code.
Don’t change Parameters
Create a new object or array in code and then proceed to add values to it. Or, use Underscore or Lodash to clone the passed object or array before using on it.
Writing Test before Coding
A test driven development (TDD) is the process of writing unit tests before the code. A lot of developers find TDD to be very helpful. In practice, TDD is a method that can be difficult to commit to all your code changes. But when it seems worth trying, it’s an excellent way to guarantee you are keeping all code testable.
I hope these tips will help you remember, to keep your code simple and functional as much as possible, this will keep your test coverage high and overall code complexity low!