john51 john51 - 5 months ago 38
AngularJS Question

How to test a loop inside an AngularJS service

I'm trying to testing service but i don't know how to test loop inside. Is it possible to test case with host.lenght===1 in different way than mock url that return host.length=1. Do I have to callFake all my code inside service to test it? Also how to test isNaN?
Here's my code:

if (host.length === 1 || !isNaN(host[host.length - 1])) {

name = a.hostname;

} else {

if (host[0] === "www") {
slice = 1;
name = host.slice(slice, host.length - 1).reverse().join(" ");

jsfiddle Demo

Answer Source

In this case, it looks simplest to just use a URL that will give you this behaviour. In my opinion, this will also be a better test as it will actually test the intent of the code, rather than just ensuring that certain methods are called. After all, this code was written to cope with different types of URL, why not test them with exactly that?

You already have a test for this url: ''. For the case you are talking about, you could use 'http://angular/about' and then '' to test the code that strips out the www. part.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download