bubblelong.blogg.se

Javascript testing
Javascript testing






#Javascript testing code

Test-doubles are, like the name suggests, replacements for pieces of code used in your tests. Sinon helps eliminate complexity in tests by allowing you to easily create so called test-doubles. I’m going to guess you probably don’t want to wait five minutes each time you run your tests.īy using Sinon, we can take both of these issues (plus many others), and eliminate the complexity. Imagine if the interval was longer, for example five minutes. What now? You could use a setTimeout in your test to wait one second, but that makes the test slow. It’s complicated to set up, and makes writing and running unit tests difficult.Īnd what if your code depends on time? Let’s say it waits one second before doing something.

javascript testing

If you want to test code making an Ajax call, how can you do that? You need to run a server and make sure it gives the exact response needed for your test. If something external affects a test, the test becomes much more complex and could fail randomly. When testing a piece of code, you don’t want to have it affected by anything outside the test. Put simply, Sinon allows you to replace the difficult parts of your tests with something that makes testing simple. What Makes Sinon so Important and Useful? But did you know there is a solution?īy using Sinon, we can make testing non-trivial code trivial! Real-life isn’t as easy as many testing tutorials make it look. With databases or networking, it’s the same thing - you need a database with the correct data, or a network server. If you use setTimeout, your test will have to wait. If you’re using Ajax, you need a server to respond to the request, so as to make your tests pass. Ajax requests, timers, dates, accessing other browser features… or if you’re using Node.js, databases are always fun, and so is network or file access.Īll of these are hard to test because you can’t control them in code.

javascript testing

In real life projects, code often does all kinds of things that make testing hard. One of the biggest stumbling blocks when writing unit tests is what to do when you have code that’s non-trivial. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! This article was peer reviewed by Mark Brown and MarcTowler.






Javascript testing