Using Jasmine, this lesson will look at testing an AngularJS service.
John Lindquist: ...let's switch gears here and test our first service. We have our before each, which is going to set up our module, and an inject, which will allow us to inject anything we declare in our module into here.
We'll describe our, let's call it a Smith service. We'll want this guy to, let's say, "It should append Smith to a name." We'll expect when we use our Smith service to get name and we'll pass in John. We'll expect that to be John Smith.
All right, that's pretty basic. Right now, we're getting Smith services not defined. Let's go ahead and define it. We'll get our Smith service through injection. We'll use the underscore way where the underscores are stripped. We'll do a Smith service. We'll set that to Smith service.
We'll split these guys up. All right, we have our Smith service. It's an unknown provider at this point. That means we need to set it up over here. That service is our Smith service. Then we'll have this. Get name. It's a function, which takes a name. That's going to return the name, plus space, Smith.
At this point, our green, we're passing our simple test, which gets John Smith from John by passing in John, appending Smith. That's what you expect it to do.
All we've really done is used our app to load up this Smith service, then set it to it. Then we're able to test it, simply by using an expect just like we've learned earlier.
Hi there. Really appreciate these videos! Up until now though, I don't think you've explained what we'd use a service for. It looks similar to factories and providers, but I'm not quite sure what canonical/happy-path use case they solve.
Hi Bernardo. Use a service when you want just one of that kind of thing throughout your application. Authentication is a good example of a service...there's only going to be one user logged into the browser that is running an AngularJS application.
A factory, though, can have multiple instances created. Watch the videos about models and you can see some of the examples of how data does and doesn't get shared for services, factories, providers, controllers, etc.