Matthew Daly's Blog

I'm a web developer in Norfolk. This is my blog...

26th November 2016 9:40 pm

Easy Static Asset Versioning in PHP

It’s prudent to cache static assets such as images, Javascript and CSS to improve performance, but that raises the issue of changes not being reflected in your site due to visitor’s browsers retaining the cached versions. Many content management systems and frameworks already handle this for you (such as Laravel’s Elixir build system), but what if you have to work with a legacy application that doesn’t do this?

Fortunately there’s a quite easy solution in PHP. Using the filemtime() function described here, we can get a Unix timestamp for when a file was last altered. This is perfect to use to identify when a file last changed, because by appending a new query string to the file name when loading it, we can trick the browser into thinking it’s a new file when it’s not, as in this example for a CodeIgniter application:

<link rel="stylesheet" type="text/css" href="<?=$path?>?v=<?=filemtime($path)?>">

Obviously, this is a bit repetitive, so you may want to refactor this into some kind of template helper to make it easier to use, but the underlying principle applies to most programming languages. For instance, if you wanted to do so in a Handlebars template, you might want to create a helper something like this:

var fs = require('fs');
var Handlebars = require('handlebars');
Handlebars.registerHelper('version', function (path) {
return path + '?v=' + fs.statSync(path).mtime.getTime();
});

Where more robust solutions such as Elixir are already available, I’d advise making full use of them. However, this technique is a quick and easy way to implement versioning for static assets in existing projects.

13th November 2016 4:15 pm

Building a Phonegap App With Laravel and Angular - Part 4

In this instalment we’ll return to the back end. What we’ve done so far is typical of the kind of proof of concept we might do for a client early on, before going back and implementing the full set of features later on. Now we’ll go back and start to improve on that rather quick-and-dirty API by making sure we follow a few best practices.

For those of you who want to follow the Laravel Phonegap tutorials, I’ve created a dedicated category here for those tutorials. This category include RSS and Atom feeds, so if you only want to read those posts, you can do so. I’ve also done the same for the Django tutorials.

The Repository pattern

One of the issues we currently have with our API is that we’re passing our Eloquent models into our controllers. This may not seem like a huge issue, but it means that our controllers are tightly coupled to the Eloquent ORM, so if we wanted to switch to another ORM, or to a completely different database such as MongoDB, we’d have to amend our controllers. That’s not good.

However, using the Repository pattern we can first of all define an interface for our repository, and then create a repository class that implements that interface. That way we can interact with the repository class in our controllers, rather than using Eloquent models directly. Then, if we want to switch databases, we merely amend the repository class to change the implementation of those methods, without having to touch our controllers. Also, it makes it much easier to test our controllers in isolation, because we can easily mock our repository class using Mockery and hard-code the response, so our tests won’t touch the database and will therefore run more quickly. We won’t touch on that this time, but it’s a very significant advantage.

If you haven’t used interfaces before in PHP, they aren’t that hard. They merely specify what methods an object implementing that method must have and what arguments they must accept, but do not specify the details of the implementation. This makes it easy to determine if a class implements an interface correctly, because it will throw an exception if it doesn’t.

<?php
namespace AnimalFriend\Repositories\Interfaces;
interface PetRepositoryInterface {
public function all();
public function findOrFail($id);
public function create($input);
}

That’s all there is to it. We define it using the interface keyword and we specify the methods it must implement. Save this file at app/Repositories/Interfaces/PetRepositoryInterface.php.

Next, we implement the repository class:

<?php
namespace AnimalFriend\Repositories;
use AnimalFriend\Pet;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface;
class EloquentPetRepository implements PetRepositoryInterface {
private $pet;
public function __construct(Pet $pet)
{
$this->pet = $pet;
}
public function all()
{
return $this->pet->all();
}
public function findOrFail($id)
{
return $this->pet->findOrFail($id);
}
public function create($input)
{
return $this->pet->create($input);
}
}

Save this to app/Repositories/EloquentPetRepository.php. Note how the methods closely mirror the underlying Eloquent methods, but they don’t need to - you could change the underlying implementation of each method, but the repository would still work in exactly the same way.

To make this work, we need to make a few changes elsewhere. In composer.json, we need to add the new Repositories folder to our classmap:

"autoload": {
"classmap": [
"database",
"app/Repositories"
],
"psr-4": {
"AnimalFriend\\": "app/"
}
},

And in app/Providers/AppServiceProvider.php, we need to bind our new files:

<?php
namespace AnimalFriend\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\PetRepositoryInterface',
'AnimalFriend\Repositories\EloquentPetRepository'
);
}
}

With that done, we can now update app/Http/Controllers/PetController.php to use the repository:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface as Pet;
class PetController extends Controller
{
private $pet;
public function __construct(Pet $pet) {
$this->pet = $pet;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Get all pets
$pets = $this->pet->all();
// Send response
return response()->json($pets, 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Get pet
$pet = $this->pet->findOrFail($id);
// Send response
return response()->json($pet, 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Our repository is now injected automatically into the controller. To make this work we need to run the following command:

$ composer dump-autoload

Running our tests should confirm that everything is still working:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 897 ms, Memory: 18.00MB
OK (12 tests, 46 assertions)

Let’s do the same for the User model. First we implement our interface in app/Repositories/Interfaces/UserRepositoryInterface.php:

<?php
namespace AnimalFriend\Repositories\Interfaces;
interface UserRepositoryInterface {
public function all();
public function findOrFail($id);
public function create($input);
}

Next we create our repository at app/Repositories/EloquentUserRepository.php:

<?php
namespace AnimalFriend\Repositories;
use AnimalFriend\User;
use AnimalFriend\Repositories\Interfaces\UserRepositoryInterface;
use JWTAuth;
use Hash;
class EloquentUserRepository implements UserRepositoryInterface {
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function all()
{
return $this->user->all();
}
public function findOrFail($id)
{
return $this->user->findOrFail($id);
}
public function create($input)
{
$user = new $this->user;
$user->email = $input['email'];
$user->name = $input['name'];
$user->password = Hash::make($input['password']);
$user->save();
// Create token
return JWTAuth::fromUser($user);
}
}

Note how we’ve moved much of the logic for creating a user into the create() method, and we return the token, not the user model. This makes sense as right now we only ever want to get a token back when we create a user. Later that may change, but there’s nothing stopping us adding a new method to implement that behaviour alongside this.

Then we update app/Http/Controllers/UserController.php to use our repository:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\UserRepositoryInterface as User;
use JWTAuth;
use Hash;
class UserController extends Controller
{
private $user;
public function __construct(User $user) {
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate request
$valid = $this->validate($request, [
'email' => 'required|email|unique:users,email',
'name' => 'required|string',
'password' => 'required|confirmed'
]);
// Create token
$token = $this->user->create($request->only(
'email',
'name',
'password'
));
// Send response
return response()->json(['token' => $token], 201);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

And add a new binding in app/Providers/AppServiceProvider.php:

<?php
namespace AnimalFriend\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\PetRepositoryInterface',
'AnimalFriend\Repositories\EloquentPetRepository'
);
$this->app->bind(
'AnimalFriend\Repositories\Interfaces\UserRepositoryInterface',
'AnimalFriend\Repositories\EloquentUserRepository'
);
}
}

Note that we bind the two sets separately - this allows Laravel to figure out which one maps to which.

Let’s run our tests to make sure nothing is broken:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 956 ms, Memory: 18.00MB
OK (12 tests, 46 assertions)

Now that we’ve got our repositories in place, we’re no longer tightly coupled to Eloquent, and have a more flexible implementation which is easier to test.

Separating our models from our JSON with Fractal

Another problem with our API is that our representation of our data is tightly coupled to our underlying implementation of our models. We therefore can’t change our models without potentially changing the data returned by the API. We need to separate our representation of our data from our actual model so that we can more easily specify the exact data we want to return, regardless of the underlying database structure.

Enter Fractal. From the website:

Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc.

In other words, Fractal lets you specify the format your data will take in one place so that it’s easier to return that data in a desired format. We’ll use Fractal to specify how we want our API responses to be formatted.

Install Fractal with the following command:

$ composer require league/fractal

Then amend the classmap in composer.json:

"autoload": {
"classmap": [
"database",
"app/Repositories",
"app/Transformers"
],
"psr-4": {
"AnimalFriend\\": "app/"
}
},

Then create the folder app/Transformers and run composer dump-autoload. We’re now ready to write our first transformer. Save this as app/Transformers/PetTransformer.php:

<?php
namespace AnimalFriend\Transformers;
use AnimalFriend\Pet;
use League\Fractal;
class PetTransformer extends Fractal\TransformerAbstract
{
public function transform(Pet $pet)
{
return [
'id' => (int) $pet->id,
'name' => (string) $pet->name,
'type' => (string) $pet->type,
'available' => (bool) $pet->available,
'picture' => (string) $pet->picture
];
}
}

The transform method specifies how we want to represent our objects with our API. We can return only those attributes we want to expose, and amend the structure as we see fit. We could easily represemt relations in whatever manner we see fit, whereas before we needed to amend our queries to return the data in the right format, which would potentially be cumbersome.

Now let’s amend PetController.php to use this:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\Repositories\Interfaces\PetRepositoryInterface as Pet;
use AnimalFriend\Transformers\PetTransformer;
use League\Fractal;
use League\Fractal\Manager;
class PetController extends Controller
{
private $pet, $fractal;
public function __construct(Pet $pet, Manager $fractal) {
$this->pet = $pet;
$this->fractal = $fractal;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Get all pets
$pets = $this->pet->all();
// Format it
$resource = new Fractal\Resource\Collection($pets, new PetTransformer);
$data = $this->fractal->createData($resource)->toArray();
// Send response
return response()->json($data, 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Get pet
$pet = $this->pet->findOrFail($id);
// Format it
$resource = new Fractal\Resource\Item($pet, new PetTransformer);
$data = $this->fractal->createData($resource)->toArray();
// Send response
return response()->json($data, 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Note that by default, Fractal places our data inside a dedicated data namespace. This is good because it leaves a place for us to put metadata such as pagination links, but it does mean our controller test has been broken. Let’s fix it:

<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
class PetControllerTest extends TestCase
{
use DatabaseMigrations;
/**
* Test fetching pets when unauthorised
*
* @return void
*/
public function testFetchingPetsWhenUnauthorised()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create request
$response = $this->call('GET', '/api/pets');
$this->assertResponseStatus(400);
}
/**
* Test fetching pets when authorised
*
* @return void
*/
public function testFetchingPets()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets', [], $headers)
->seeJsonStructure([
'data' => [
'*' => [
'id',
'name',
'type',
'available',
'picture'
]
]
]);
$this->assertResponseStatus(200);
}
/**
* Test fetching pet when unauthorised
*
* @return void
*/
public function testFetchingPetWhenUnauthorised()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Send request
$response = $this->call('GET', '/api/pets/'.$pet->id);
$this->assertResponseStatus(400);
}
/**
* Test fetching pet which does not exist
*
* @return void
*/
public function testFetchingPetDoesNotExist()
{
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets/1', [], $headers);
$this->assertResponseStatus(404);
}
/**
* Test fetching pet when authorised
*
* @return void
*/
public function testFetchingPet()
{
// Create a Pet
$pet = factory(AnimalFriend\Pet::class)->create([
'name' => 'Freddie',
'type' => 'Cat',
]);
$this->seeInDatabase('pets', ['type' => 'Cat']);
// Create a User
$user = factory(AnimalFriend\User::class)->create([
'name' => 'bobsmith',
'email' => 'bob@example.com',
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create request
$token = JWTAuth::fromUser($user);
$headers = array(
'Authorization' => 'Bearer '.$token
);
// Send it
$this->json('GET', '/api/pets/'.$pet->id, [], $headers)
->seeJsonStructure([
'data' => [
'id',
'name',
'type',
'available',
'picture'
]
]);
$this->assertResponseStatus(200);
}
}

We’re also going to amend our test settings to use the array backend for the cache, as this does not require any external dependencies, but still allows us to tag our cache keys (I’ll cover that in a future instalment). Change the cache settings in phpunit.xml as follows:

<env name="CACHE_DRIVER" value="array"/>

Let’s run our tests to make sure everything’s fine:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 859 ms, Memory: 18.00MB
OK (12 tests, 44 assertions)

At present our User controller doesn’t actually return anything, and the auth only ever returns the token, so it’s not worth while adding a transformer now.

Wrapping up

That ends this lesson. We haven’t added any functionality, but we have improved the design of our API, and we’re now ready to develop it further. As usual, the backend repository has been tagged as lesson-4.

Next time we’ll start adding the additional functionality we need to our API.

24th October 2016 12:25 am

Creating An Azure Storage Adapter for Laravel

About a year ago I was working on my first non-trivial Laravel application. The client had, for their own reasons, wanted to use Microsoft’s Azure platform, particularly for its blob storage functionality, which is somewhat comparable to Amazon S3. Now, Laravel has the excellent Storage facade that allows consistent access to both local files and those stored on various file hosting services, which is built on top of Flysystem. Flysystem has an Azure driver, but the Laravel storage doesn’t include support for it, so at the time I resigned myself to using Flysystem directly, which wasn’t actually that bad, but not ideal.

A few days ago I stumbled across this section of the Laravel documentation, which had me kicking myself. It’s actually trivially easy to implement a custom filesystem for Laravel if it already has a Flysystem adapter, as demonstrated in their Dropbox implementation in the docs. Using this as a guide, I was able to produce the following service provider for using Azure as a storage backend very quickly:

<?php
namespace App\Providers;
use Storage;
use League\Flysystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Azure\AzureAdapter;
use WindowsAzure\Common\ServicesBuilder;
class AzureStorageServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Storage::extend('azure', function($app, $config) {
$endpoint = sprintf(
'DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s',
$config['name'],
$config['key']
);
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($endpoint);
return new Filesystem(new AzureAdapter($blobRestProxy, $config['container']));
});
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}

This should be saved as app/Providers/AzureStorageServiceProvider.php. You also need to add this to the list of service providers in config/app.php:

        App\Providers\AzureStorageServiceProvider::class,

And add this to config/filesystems.php:

'azure' => [
'driver' => 'azure',
'name' => env('STORAGE_NAME'),
'key' => env('STORAGE_KEY'),
'container' => env('STORAGE_CONTAINER'),
],

I like to also set my storage backend using environment variables in this file, as in this example:

'default' => env('STORAGE_BACKEND', 'local'),

That way we can easily set a different backend for testing, development and production so we don’t upload files when running PHPUnit. You can also keep your other config settings in your .env file, which is always a better idea than keeping it under version control. You also need to install the microsoft/windowsazure and league/flysystem-azure packages via Composer for this to work.

As I’ve since changed jobs it’s unlikely I’ll ever actually use this Azure integration in production - it’s not a service I’d choose of my own accord to use. However, since it’s so straightforward to implement an adapter like this I imagine I may be doing something similar - I’m currently working on a web app that uses MongoDB for some of its data and currently stores files locally, so it might make sense to create a GridFS integration along similar lines. It may also be useful for someone else, so feel free to use it if you wish.

16th October 2016 6:10 pm

Building a Phonegap App With Laravel and Angular - Part 3

Apologies for how long it’s taken for this post to appear. I’ve got a lot on my plate at present as I recently started a new job, so I haven’t been able to devote as much time to this series as I’d like.

In this instalment we’ll begin extending our app beyond the basic authentication we’ve already implemented. We’ll start by adding the means to sign up, before adding the list of pets.

Adding a signup method to our backend

We’ll create a controller for our users in the Laravel backend. First we’ll create our tests:

$ php artisan make:test UserControllerTest

We’ll create three tests. The first will check to see that an invalid request raises the correct status code (422). The second will check that a valid request returns the correct status code (201) and creates the user. The third will check that trying to create a duplicate user raises an error. Here they are - they should be saved in the new tests/UserControllerTest.php file:

<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
class UserControllerTest extends TestCase
{
/**
* Test creating a user - invalid
*
* @return void
*/
public function testPostingInvalidUser()
{
// Create a request
$data = array(
'name' => 'Bob Smith',
'email' => 'bob@example.com'
);
$this->json('POST', '/api/users', $data);
$this->assertResponseStatus(422);
}
/**
* Test creating a user
*
* @return void
*/
public function testPostingUser()
{
// Create a request
$data = array(
'name' => 'Bob Smith',
'email' => 'bob@example.com',
'password' => 'password',
'password_confirmation' => 'password'
);
$this->json('POST', '/api/users', $data);
$this->assertResponseStatus(201);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Check user exists
$saved = User::first();
$this->assertEquals($saved->email, 'bob@example.com');
$this->assertEquals($saved->name, 'Bob Smith');
}
/**
* Test creating a duplicate user
*
* @return void
*/
public function testPostingDuplicateUser()
{
// Create user
$user = factory(AnimalFriend\User::class)->create([
'name' => 'Bob Smith',
'email' => 'bob@example.com',
'password' => 'password'
]);
$this->seeInDatabase('users', ['email' => 'bob@example.com']);
// Create a request
$data = array(
'name' => 'Bob Smith',
'email' => 'bob@example.com',
'password' => 'password',
'password_confirmation' => 'password'
);
$this->json('POST', '/api/users', $data);
$this->assertResponseStatus(422);
}
}

Note the use of $this->json() to make the request. This method is ideal for testing a REST API.

Running our tests should confirm that they fail:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
........FFF. 12 / 12 (100%)
Time: 827 ms, Memory: 18.00MB
There were 3 failures:
1) UserControllerTest::testPostingInvalidUser
Expected status code 422, got 404.
Failed asserting that 404 matches expected 422.
/home/matthew/Projects/mynewanimalfriend-backend/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:648
/home/matthew/Projects/mynewanimalfriend-backend/tests/UserControllerTest.php:21
2) UserControllerTest::testPostingUser
Expected status code 201, got 404.
Failed asserting that 404 matches expected 201.
/home/matthew/Projects/mynewanimalfriend-backend/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:648
/home/matthew/Projects/mynewanimalfriend-backend/tests/UserControllerTest.php:39
3) UserControllerTest::testPostingDuplicateUser
Expected status code 422, got 404.
Failed asserting that 404 matches expected 422.
/home/matthew/Projects/mynewanimalfriend-backend/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:648
/home/matthew/Projects/mynewanimalfriend-backend/tests/UserControllerTest.php:71
FAILURES!
Tests: 12, Assertions: 43, Failures: 3.

Next, we create our new controller:

$ php artisan make:controller UserController --resource

Let’s populate it:

<?php
namespace AnimalFriend\Http\Controllers;
use Illuminate\Http\Request;
use AnimalFriend\Http\Requests;
use AnimalFriend\User;
use JWTAuth;
use Hash;
class UserController extends Controller
{
private $user;
public function __construct(User $user) {
$this->user = $user;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate request
$valid = $this->validate($request, [
'email' => 'required|email|unique:users,email',
'name' => 'required|string',
'password' => 'required|confirmed',
]);
// Create user
$user = new $this->user;
$user->email = $request->input('email');
$user->name = $request->input('name');
$user->password = Hash::make($request->input('password'));
$user->save();
// Create token
$token = JWTAuth::fromUser($user);
// Send response
return response()->json(['token' => $token], 201);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

For now we’ll leave the other methods blank, but we’ll be using them later so we won’t get rid of them. At the top, note we load not only the User model, but also the JWTAuth and Hash facades. We use JWTAuth::fromUser() to return a JSON web token for the given user model.

In the store() method we first of all use Laravel’s validation support to validate our input. We specify that the user must provide a unique email address, a username, and a password, which must be confirmed. Note that we don’t need to specify an action if the request is invalid, as Laravel will do that for us. Also, note that the confirmed rule means that the password field must be accompanied by a matching password_confirmation field.

Next, we create the user. Note that we hash the password before storing it, which is a best practice (storing passwords in plain text is a REALLY bad idea!). Then we create the token for the new user and return it. From then on, the user can use that token to authenticate their requests.

We also need to add this route in routes/api.php:

Route::resource('users', 'UserController');

Let’s check the test passes:

$ vendor/bin/phpunit
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
............ 12 / 12 (100%)
Time: 905 ms, Memory: 20.00MB
OK (12 tests, 46 assertions)

Building the registration in the app

With registration in place on the server side, we can move back to the app. We need to create another route for the registration form. Add this to test/routes.spec.js:

it('should map register route to register controller', function () {
inject(function ($route) {
expect($route.routes['/register'].controller).toBe('RegisterCtrl');
expect($route.routes['/register'].templateUrl).toEqual('templates/register.html');
});
});

Running the tests should confirm that this fails. So next you should add this to the route provider section of js/main.js:

.when('/register', {
templateUrl: 'templates/register.html',
controller: 'RegisterCtrl'
})

We also need to allow the register path to be accessed when not logged in:

.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
if ($location.path() !== '/login' && $location.path() !== '/register') {
$location.path('/login');
}
}
});
}])

Our next step is to create a service representing the User endpoint. Here’s the test for it:

describe('User service', function () {
var mockBackend, User;
beforeEach(inject(function (_User_, _$httpBackend_) {
User = _User_;
mockBackend = _$httpBackend_;
}));
it('can create a new user', function () {
mockBackend.expectPOST('http://localhost:8000/api/users', '{"email":"bob@example.com","name":"bobsmith","password":"password","password_confirmation":"password"}').respond({token: 'mytoken'});
var user = new User({
email: 'bob@example.com',
name: 'bobsmith',
password: 'password',
password_confirmation: 'password'
});
user.$save(function (response) {
expect(response).toEqualData({token: 'mytoken'});
});
mockBackend.flush();
});
});

We’re only interested in using this model to create new users at this point, so this is the full scope of this test for now. Make sure the test fails, then we’re ready to create the new service in js/services.js:

.factory('User', function ($resource) {
return $resource('http://localhost:8000/api/users/:id', null, {
'update': { method: 'PATCH' }
});
})

Note that angular-resource does not support the PUT or PATCH methods by default, but as shown here it’s easy to implement it ourselves. That should be sufficient to make our test pass.

Next, we need to create the controller for registration. Here’s the test for it:

describe('Register Controller', function () {
var mockBackend, scope;
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
mockBackend = _$httpBackend_;
scope = $rootScope.$new();
$controller('RegisterCtrl', {
$scope: scope
});
}));
// Test controller scope is defined
it('should define the scope', function () {
expect(scope).toBeDefined();
});
// Test doRegister is defined
it('should define the register method', function () {
expect(scope.doRegister).toBeDefined();
});
// Test doRegister works
it('should allow the user to register', function () {
// Mock the backend
mockBackend.expectPOST('http://localhost:8000/api/users', '{"email":"user@example.com","name":"bobsmith","password":"password","password_confirmation":"password"}').respond({token: 123});
// Define login data
scope.credentials = {
email: 'user@example.com',
name: "bobsmith",
password: 'password',
password_confirmation: 'password'
};
// Submit the request
scope.doRegister();
// Flush the backend
mockBackend.flush();
// Check login complete
expect(localStorage.getItem('authHeader')).toEqual('Bearer 123');
});
});

Make sure the test fails before proceeding. Our RegisterCtrl is very similar to the login controller:

.controller('RegisterCtrl', function ($scope, $location, User, Auth) {
$scope.doRegister = function () {
var user = new User($scope.credentials);
user.$save(function (response) {
if (response.token) {
// Set up auth service
Auth.setUser(response.token);
// Redirect
$location.path('/');
}
}, function (err) {
alert('Unable to log in - please check your details are correct');
});
};
})

Check the tests pass,and we’re ready to move on to creating our HTML template. Save this as www/templates/register.html:

<md-content md-theme="default" layout-gt-sm="row" layout-padding>
<div>
<md-input-container class="md-block">
<label>Email</label>
<input ng-model="credentials.email" type="email">
</md-input-container>
<md-input-container class="md-block">
<label>Username</label>
<input ng-model="credentials.name" type="text">
</md-input-container>
<md-input-container class="md-block">
<label>Password</label>
<input ng-model="credentials.password" type="password">
</md-input-container>
<md-input-container class="md-block">
<label>Confirm Password</label>
<input ng-model="credentials.password_confirmation" type="password">
</md-input-container>
<md-button class="md-raised md-primary" ng-click="doRegister()">Submit</md-button>
<md-button class="md-raised md-primary" href="/login">Log in</md-button>
</div>
</md-content>

It’s very similar to our login template. Speaking of which, we need to add a link to this route there:

<md-content md-theme="default" layout-gt-sm="row" layout-padding>
<div>
<md-input-container class="md-block">
<label>Email</label>
<input ng-model="credentials.email" type="email" />
</md-input-container>
<md-input-container class="md-block">
<label>Password</label>
<input ng-model="credentials.password" type="password" />
</md-input-container>
<md-button class="md-raised md-primary" ng-click="doLogin()">Submit</md-button>
<md-button class="md-raised md-primary" href="register">Register</md-button>
</div>
</md-content>

With that done, you should now be able to run the Gulp server for the app with gulp and the Laravel backend with php artisan serve and create a new user account.

Adding pets to the home page

Our final task for this lesson is to display a list of pets on the home page. Later we’ll refine that functionality, but for now we’ll just get a list of all current pets and display them. First we need to write a test for our Pet service:

describe('Pet service', function () {
var mockBackend, Pet;
beforeEach(inject(function (_Pet_, _$httpBackend_) {
Pet = _Pet_;
mockBackend = _$httpBackend_;
}));
it('can fetch pets', function () {
mockBackend.expectGET('http://localhost:8000/api/pets').respond([{id:1,name:"Freddie",type:"Cat"}]);
expect(Pet).toBeDefined();
var pets = Pet.query();
mockBackend.flush();
expect(pets).toEqualData([{id: 1,name:"Freddie",type:"Cat"}]);
});
});

Once you know that fails, it’s time to implement the service:

.factory('Pet', function ($resource) {
return $resource('http://localhost:8000/api/pets/:id', null, {
'update': { method: 'PATCH' }
});
})

Next, we want to add the pets to the scope of the home controller. Amend the test for it as follows:

describe('Home Controller', function () {
var pets, scope;
beforeEach(inject(function ($rootScope, $controller, Pet) {
pets = Pet;
scope = $rootScope.$new();
$controller('HomeCtrl', {
$scope: scope,
pets: [{id:1},{id:2}]
});
}));
// Test controller scope is defined
it('should define the scope', function () {
expect(scope).toBeDefined();
});
// Test pets
it('should define the pets', function () {
expect(scope.pets).toEqualData([{id: 1}, {id: 2}]);
});
});

We check to see if the scope contains the pets variable. Once you have a failing test, amend the home controller as follows:

.controller('HomeCtrl', function ($scope, Pet, pets) {
$scope.pets = pets;
});

We could fetch the via AJAX inside the controller, but there’s a better way. We’ll create a loader for the pet data and have it resolve that before the page is displayed. To do so, first we need to add the loader service to js/services.js:

.factory('PetsLoader', ['Pet', '$q', function (Pet, $q) {
return function () {
var delay = $q.defer();
Pet.query(function (response) {
delay.resolve(response);
}, function () {
delay.reject('Unable to fetch pets');
});
return delay.promise;
};
}])

Then we set that route up to resolve it in js/main.js:

.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl',
resolve: {
pets: ['PetsLoader', function (PetsLoader) {
return PetsLoader();
}]
}
})

Now, when we load that route, it will first of all fetch those pets and populate $scope.pets with them.

Now, we need to have some pets in the database, so we’ll make a seeder for it. Head back to the backend and run this command:

$ php artisan make:seeder PetTableSeeder

Then amend the file at database/seeds/PetTableSeeder.php as follows:

<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class PetTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Add Pets
DB::table('pets')->insert([[
'name' => 'Freddie',
'type' => 'Cat',
'available' => 1,
'picture' => 'https://placekitten.com/300/300',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
], [
'name' => 'Sophie',
'type' => 'Cat',
'available' => 1,
'picture' => 'https://placekitten.com/300/300',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]]);
}
}

And we need to update database/seeds/DatabaseSeeder.php to call our seeder:

<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(PetTableSeeder::class);
}
}

For now we’ll use placeholder images, but at a later point our backend will be set up to use images uploaded from the admin. Then we need to refresh our migrations and apply the seeders:

$ php artisan migrate:refresh
$ php artisan db:seed

Now we just need to amend our home template to show the pets and we’re done for today:

<md-toolbar>
<div class="md-toolbar-tools">
<md-button aria-label="Log out" href="/logout">
Log out
</md-button>
</div>
</md-toolbar>
<div layout="column" flex="grow" layout-align="center stretch">
<md-card md-theme="default" ng-repeat="pet in pets">
<md-card-title>
<md-card-title-text>
<span class="md-headline">{{ pet.name }}</span>
<span class="md-subhead">{{ pet.type }}</span>
</md-card-title-text>
</md-card-title>
<md-card-content>
<img class="md-card-image md-media-lg" ng-src="{{ pet.picture }}"></img>
</md-card-content>
</md-card>
</div>

Now we can see our pets in the app.

Wrapping up

That’s enough for today - the fact that we can log in and out, register, and view the home page is sufficient as a proof of concept for a client. As usual, the results are on Github, tagged lesson-3.

Next time, we’ll concentrate exclusively on the back end. We’ll build upon what we already have using Laravel to create a full REST API for our app. In a later instalment, we’ll move on to build our admin interface for the staff, before switching back to finish off the app. I hope you’ll join me then.

18th September 2016 11:18 pm

Building a Phonegap App With Laravel and Angular - Part 2

In this lesson, the initial scope of the app will be extremely simple. We will implement functionality that:

  • Allows users to log in and out
  • Displays the home page

That’s fairly simple, and easily achievable within a fairly short timeframe. We’ll also write automated tests for our app. By the end of this lesson, we’ll have built a first pass for our app using Angular.js.

NOTE: As at time of writing, Angular 2 has just come out. I’m using Angular 1 here, and the two are not compatible, so make sure you’re using Angular 1.

Creating our app

Start by creating a new folder, separate from the backend, for the app. Then, in there, run the following command:

$ npm init -y

Then let’s install our dependencies:

$ npm install --save-dev gulp karma karma-browserify karma-phantomjs-launcher browserify angular angular-route angular-mocks angular-animate angular-messages angular-sanitize angular-material angular-resource vinyl-buffer vinyl-source-stream gulp-sass karma-coverage karma-jasmine jasmine-core gulp-webserver

We’re going to use Angular Material for our user interface as it includes support out of the box for swiping left and right. You’ll notice it mentioned as one of the dependencies above.

We’ll also use Karma for running our tests. Save the following as karma.conf.js:

module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'node_modules/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-material/angular-material-mocks.js',
'js/*.js',
'test/*.js'
],
exclude: [
],
preprocessors: {
'js/*.js': ['browserify', 'coverage'],
'tests/js': ['browserify']
},
browserify: {
debug: true
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: true,
coverageReporter: {
dir : 'coverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: 'report-cobertura' }
]
}
});
};

This is our Karma configuration. Karma can run the same test in multiple browsers. Here we’re going to use PhantomJS, but it’s trivial to amend the browsers section to add more. You just need to make sure you install the appropriate launchers for those browsers.

We’ll use Gulp to build the app. Here’s the gulpfile.js:

var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var sass = require('gulp-sass');
var server = require('gulp-webserver');
var paths = {
scripts: ['js/*.js'],
styles: ['sass/*.scss']
};
gulp.task('sass', function() {
gulp.src('sass/style.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('www/css'));
});;
gulp.task('js', function () {
return browserify({ entries: ['js/main.js'], debug: true })
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(gulp.dest('www/js/'));
});
gulp.task('server', function () {
gulp.src('www/')
.pipe(server({
livereload: true,
open: true,
port: 5000
}));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['js']);
gulp.watch(paths.styles, ['sass']);
});
gulp.task('default', ['sass','js','server', 'watch']);

Note that we’re going to be using Browserify to handle our dependencies. If you haven’t used it before, it lets you use the require() syntax from Node.js to include other JavaScript files, including ones available via NPM such as jQuery or Angular, allowing you to compile them all into a single file.

We should be able to test and run the app using NPM, so add these scripts to package.json:

"scripts": {
"test": "karma start",
"run": "gulp"
},

We also need an HTML file. Save this as www/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
<title>My New Animal Friend</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div>
<div ng-app="mynewanimalfriend" ng-cloak>
<div ng-view></div>
</div>
</div>
</body>
<script language="javascript" type="text/javascript" src="/js/bundle.js"></script>
</html>

Note the use of the Angular directives. ng-app denotes the name of the app namespace, ng-cloak hides the application until it’s fully loaded, and ng-view denotes the area containing our content.

You should also create the files js/main.js, sass/style.scss, and the test folder.

Creating our first routes

Our first task is to create the routes we need. Our default route will be /, representing the home page. However, users will need to be logged in to see this. Otherwise, they should be redirected to the login route, which will be /login, appropriately enough. We’ll also have a /logout route, which should be self-explanatory.

Before we implement these routes, we need to write a test for them. We’ll start with our login route, and we’ll test that for this route, the controller will be LoginCtrl and the template will be templates/login.html. The significance of these will become apparent later. Save this as test/routes.spec.js:

'use strict';
describe('Routes', function () {
beforeEach(angular.mock.module('mynewanimalfriend'));
it('should map login route to login controller', function () {
inject(function ($route) {
expect($route.routes['/login'].controller).toBe('LoginCtrl');
expect($route.routes['/login'].templateUrl).toEqual('templates/login.html');
});
});
});

Note the beforeEach() hook. This is used to set up the application.

We can run this test with npm test as that calls Karma directly. Note that we’re using Jasmine to write our tests.

$ npm test
> mynewanimalfriend-app@1.0.0 test /home/matthew/Projects/mynewanimalfriend-app
> karma start
12 09 2016 22:22:34.168:DEBUG [config]: autoWatch set to false, because of singleRun
12 09 2016 22:22:34.172:DEBUG [plugin]: Loading karma-* from /home/matthew/Projects/mynewanimalfriend-app/node_modules
12 09 2016 22:22:34.176:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-browserify.
12 09 2016 22:22:34.314:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-coverage.
12 09 2016 22:22:34.484:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine.
12 09 2016 22:22:34.485:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-phantomjs-launcher.
12 09 2016 22:22:34.535:DEBUG [framework.browserify]: created browserify bundle: /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
12 09 2016 22:22:34.553:DEBUG [framework.browserify]: add bundle to config.files at position 3
12 09 2016 22:22:34.559:DEBUG [web-server]: Instantiating middleware
12 09 2016 22:22:34.569:DEBUG [reporter]: Trying to load reporter: coverage
12 09 2016 22:22:34.570:DEBUG [reporter]: Trying to load color-version of reporter: coverage (coverage_color)
12 09 2016 22:22:34.571:DEBUG [reporter]: Couldn't load color-version.
12 09 2016 22:22:34.596:DEBUG [framework.browserify]: updating js/main.js in bundle
12 09 2016 22:22:34.597:DEBUG [framework.browserify]: building bundle
12 09 2016 22:22:35.302:DEBUG [framework.browserify]: bundling
12 09 2016 22:22:35.328:DEBUG [preprocessor.coverage]: Processing "/home/matthew/Projects/mynewanimalfriend-app/js/main.js".
12 09 2016 22:22:35.345:INFO [framework.browserify]: bundle built
12 09 2016 22:22:35.352:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
12 09 2016 22:22:35.352:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
12 09 2016 22:22:35.361:INFO [launcher]: Starting browser PhantomJS
12 09 2016 22:22:35.361:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-17657666
12 09 2016 22:22:35.364:DEBUG [launcher]: /home/matthew/Projects/mynewanimalfriend-app/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /tmp/karma-17657666/capture.js
12 09 2016 22:22:35.466:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/client.html
12 09 2016 22:22:35.478:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/karma.js
12 09 2016 22:22:35.541:DEBUG [karma]: A browser has connected on socket /#dQYjOD4F_HJwPXiYAAAA
12 09 2016 22:22:35.564:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=dQYjOD4F_HJwPXiYAAAA
12 09 2016 22:22:35.629:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#dQYjOD4F_HJwPXiYAAAA with id 17657666
12 09 2016 22:22:35.630:DEBUG [launcher]: PhantomJS (id 17657666) captured in 0.277 secs
12 09 2016 22:22:35.642:DEBUG [phantomjs.launcher]:
12 09 2016 22:22:35.643:DEBUG [middleware:karma]: custom files null null
12 09 2016 22:22:35.644:DEBUG [middleware:karma]: Serving static request /context.html
12 09 2016 22:22:35.646:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.html
12 09 2016 22:22:35.650:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b1682a1eb50e00abf147fc1fb28e31006d499aae /
12 09 2016 22:22:35.650:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
12 09 2016 22:22:35.652:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
12 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-material/angular-material-mocks.js?9f31553e4bbbad4d6b52638351e3a274352311c2 /
12 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
12 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
12 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
12 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7975a273517f1eb29d7bd018790fd4c7b9a485d5 /
12 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
12 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular/angular.min.js?78069f9f3a9ca9652cb04c13ccb0670d747666b8 /
12 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
12 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-mocks/angular-mocks.js?cc56136dc551d94abe8195cf8475eb27a3aa3c4b /
12 09 2016 22:22:35.657:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
12 09 2016 22:22:35.657:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
12 09 2016 22:22:35.658:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
12 09 2016 22:22:35.658:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
12 09 2016 22:22:35.659:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
12 09 2016 22:22:35.659:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
12 09 2016 22:22:35.660:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.js
12 09 2016 22:22:35.661:DEBUG [middleware:source-files]: Requesting /absolute/tmp/f8c46bd8d72c5b8578e64552192273be.browserify?8ffde4eef27d38e92cc62da4e8dd0ffa5a3a4a4c /
12 09 2016 22:22:35.661:DEBUG [middleware:source-files]: Fetching /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
12 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Requesting /base/js/main.js?41c850cecc07c24d7cd0421e914bd2420671e573 /
12 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/js/main.js
12 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Requesting /base/test/routes.spec.js?92b15bb7c24bc6ead636994fb1c737b91727d887 /
12 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
12 09 2016 22:22:35.663:DEBUG [web-server]: serving (cached): /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
12 09 2016 22:22:35.664:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/js/main.js
12 09 2016 22:22:35.664:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
PhantomJS 2.1.1 (Linux 0.0.0) Routes should map login route to login controller FAILED
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=mynewanimalfriend&p1=%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.8%2F%24injector%2Fnomod%3Fp0%3Dmynewanimalfriend%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A25%3A111%0Ab%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A24%3A143%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A24%3A489%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A39%3A473%0Aq%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A7%3A359%0Ag%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A39%3A320%0Acb%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A43%3A337%0AworkFn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular-mocks%2Fangular-mocks.js%3Fcc56136dc551d94abe8195cf8475eb27a3aa3c4b%3A3074%3A60%0Ainject%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular-mocks%2Fangular-mocks.js%3Fcc56136dc551d94abe8195cf8475eb27a3aa3c4b%3A3054%3A46%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Ftest%2Froutes.spec.js%3F92b15bb7c24bc6ead636994fb1c737b91727d887%3A5%3A11%0AattemptSync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1942%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1930%3A20%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A367%3A28%0Afn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2568%3A44%0AattemptAsync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1972%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1927%3A21%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Afn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2553%3A31%0AattemptAsync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1972%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1927%3A21%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2415%3A25%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A772%3A24%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fkarma-jasmine%2Flib%2Fadapter.js%3F7975a273517f1eb29d7bd018790fd4c7b9a485d5%3A320%3A23%0Aloaded%40http%3A%2F%2Flocalhost%3A9876%2Fcontext.js%3A151%3A17%0Aglobal%20code%40http%3A%2F%2Flocalhost%3A9876%2Fcontext.html%3A50%3A28 in node_modules/angular/angular.min.js (line 40)
node_modules/angular/angular.min.js:40:260
q@node_modules/angular/angular.min.js:7:359
g@node_modules/angular/angular.min.js:39:320
cb@node_modules/angular/angular.min.js:43:337
workFn@node_modules/angular-mocks/angular-mocks.js:3074:60
inject@node_modules/angular-mocks/angular-mocks.js:3054:46
test/routes.spec.js:5:11
loaded@http://localhost:9876/context.js:151:17
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.044 secs / 0.006 secs)
12 09 2016 22:22:35.778:DEBUG [karma]: Run complete, exiting.
12 09 2016 22:22:35.778:DEBUG [launcher]: Disconnecting all browsers
12 09 2016 22:22:35.778:DEBUG [framework.browserify]: cleaning up
12 09 2016 22:22:35.782:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-html
12 09 2016 22:22:35.876:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-cobertura
12 09 2016 22:22:35.880:DEBUG [launcher]: Process PhantomJS exited with code 0
12 09 2016 22:22:35.881:DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-17657666
12 09 2016 22:22:35.884:DEBUG [launcher]: Finished all browsers
npm ERR! Test failed. See above for more details.

Now that we have a failing test, we can set about making it pass. Save this at js/main.js:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
});

As mentioned earlier, because we’re using Browserify, we can use the require() syntax to import our dependencies. Note we also give our module a name and specify the dependencies. Finally, note that we use $routeProvider to set up our first route, and we map the template URL and controller to match our test.

Let’s run the test again:

$ npm test
> mynewanimalfriend-app@1.0.0 test /home/matthew/Projects/mynewanimalfriend-app
> karma start
12 09 2016 22:35:51.231:DEBUG [config]: autoWatch set to false, because of singleRun
12 09 2016 22:35:51.235:DEBUG [plugin]: Loading karma-* from /home/matthew/Projects/mynewanimalfriend-app/node_modules
12 09 2016 22:35:51.237:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-browserify.
12 09 2016 22:35:51.354:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-coverage.
12 09 2016 22:35:51.496:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine.
12 09 2016 22:35:51.497:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-phantomjs-launcher.
12 09 2016 22:35:51.547:DEBUG [framework.browserify]: created browserify bundle: /tmp/02002698e6d413a542186462d3a0a6ce.browserify
12 09 2016 22:35:51.559:DEBUG [framework.browserify]: add bundle to config.files at position 3
12 09 2016 22:35:51.564:DEBUG [web-server]: Instantiating middleware
12 09 2016 22:35:51.581:DEBUG [reporter]: Trying to load reporter: coverage
12 09 2016 22:35:51.582:DEBUG [reporter]: Trying to load color-version of reporter: coverage (coverage_color)
12 09 2016 22:35:51.582:DEBUG [reporter]: Couldn't load color-version.
12 09 2016 22:35:51.602:DEBUG [framework.browserify]: updating js/main.js in bundle
12 09 2016 22:35:51.603:DEBUG [framework.browserify]: building bundle
12 09 2016 22:35:52.306:DEBUG [framework.browserify]: bundling
12 09 2016 22:35:54.095:DEBUG [preprocessor.coverage]: Processing "/home/matthew/Projects/mynewanimalfriend-app/js/main.js".
12 09 2016 22:35:54.170:INFO [framework.browserify]: bundle built
12 09 2016 22:35:54.189:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
12 09 2016 22:35:54.189:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
12 09 2016 22:35:54.197:INFO [launcher]: Starting browser PhantomJS
12 09 2016 22:35:54.198:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-91342786
12 09 2016 22:35:54.201:DEBUG [launcher]: /home/matthew/Projects/mynewanimalfriend-app/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /tmp/karma-91342786/capture.js
12 09 2016 22:35:54.300:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/client.html
12 09 2016 22:35:54.308:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/karma.js
12 09 2016 22:35:54.366:DEBUG [karma]: A browser has connected on socket /#FpcuZAJUT-u6Dl4sAAAA
12 09 2016 22:35:54.386:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=FpcuZAJUT-u6Dl4sAAAA
12 09 2016 22:35:54.442:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#FpcuZAJUT-u6Dl4sAAAA with id 91342786
12 09 2016 22:35:54.442:DEBUG [launcher]: PhantomJS (id 91342786) captured in 0.253 secs
12 09 2016 22:35:54.447:DEBUG [phantomjs.launcher]:
12 09 2016 22:35:54.448:DEBUG [middleware:karma]: custom files null null
12 09 2016 22:35:54.448:DEBUG [middleware:karma]: Serving static request /context.html
12 09 2016 22:35:54.449:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.html
12 09 2016 22:35:54.451:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b1682a1eb50e00abf147fc1fb28e31006d499aae /
12 09 2016 22:35:54.451:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
12 09 2016 22:35:54.452:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
12 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-material/angular-material-mocks.js?9f31553e4bbbad4d6b52638351e3a274352311c2 /
12 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
12 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
12 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
12 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7975a273517f1eb29d7bd018790fd4c7b9a485d5 /
12 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
12 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-mocks/angular-mocks.js?cc56136dc551d94abe8195cf8475eb27a3aa3c4b /
12 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
12 09 2016 22:35:54.455:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular/angular.min.js?78069f9f3a9ca9652cb04c13ccb0670d747666b8 /
12 09 2016 22:35:54.455:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
12 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
12 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
12 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
12 09 2016 22:35:54.456:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
12 09 2016 22:35:54.457:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
12 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Requesting /absolute/tmp/02002698e6d413a542186462d3a0a6ce.browserify?f4c82dc0618d979f84c89967ea1c412e646a5fe5 /
12 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Fetching /tmp/02002698e6d413a542186462d3a0a6ce.browserify
12 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Requesting /base/js/main.js?41c850cecc07c24d7cd0421e914bd2420671e573 /
12 09 2016 22:35:54.459:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/js/main.js
12 09 2016 22:35:54.460:DEBUG [middleware:source-files]: Requesting /base/test/routes.spec.js?92b15bb7c24bc6ead636994fb1c737b91727d887 /
12 09 2016 22:35:54.461:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
12 09 2016 22:35:54.461:DEBUG [web-server]: serving (cached): /tmp/02002698e6d413a542186462d3a0a6ce.browserify
12 09 2016 22:35:54.496:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/js/main.js
12 09 2016 22:35:54.497:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
12 09 2016 22:35:54.497:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.js
12 09 2016 22:35:54.582:DEBUG [phantomjs.launcher]: WARNING: Tried to load angular more than once.
PhantomJS 2.1.1 (Linux 0.0.0) LOG: 'WARNING: Tried to load angular more than once.'
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.004 secs / 0.358 secs)
12 09 2016 22:35:55.003:DEBUG [karma]: Run complete, exiting.
12 09 2016 22:35:55.003:DEBUG [launcher]: Disconnecting all browsers
12 09 2016 22:35:55.003:DEBUG [framework.browserify]: cleaning up
12 09 2016 22:35:55.006:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-html
12 09 2016 22:35:55.078:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-cobertura
12 09 2016 22:35:55.082:DEBUG [launcher]: Process PhantomJS exited with code 0
12 09 2016 22:35:55.082:DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-91342786
12 09 2016 22:35:55.085:DEBUG [launcher]: Finished all browsers

Our first test has passed. Let’s add tests for the other routes:

'use strict';
describe('Routes', function () {
beforeEach(angular.mock.module('mynewanimalfriend'));
it('should map default route to home controller', function () {
inject(function ($route) {
expect($route.routes['/'].controller).toBe('HomeCtrl');
expect($route.routes['/'].templateUrl).toEqual('templates/home.html');
});
});
it('should map login route to login controller', function () {
inject(function ($route) {
expect($route.routes['/login'].controller).toBe('LoginCtrl');
expect($route.routes['/login'].templateUrl).toEqual('templates/login.html');
});
});
it('should map logout route to logout controller', function () {
inject(function ($route) {
expect($route.routes['/logout'].controller).toBe('LogoutCtrl');
expect($route.routes['/logout'].templateUrl).toEqual('templates/login.html');
});
});
});

Note that the logout route uses the login template. This is because all it will do is redirect the user to the login form.

For the sake of brevity I won’t display the test output, but two of these tests should now fail. We can easily set up the new routes in js/main.js:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.when('/logout', {
templateUrl: 'templates/login.html',
controller: 'LogoutCtrl'
});
});

That’s looking good so far. But what if someone navigates to a URL that doesn’t exist? Our router should handle that. Add this to the test:

it('should redirect other or empty routes to the home controller', function () {
inject(function ($route) {
expect($route.routes[null].redirectTo).toEqual('/')
});
});

Once again, the test should fail. Fixing it is fairly straightforward - we’ll use the otherwise() method to define a fallback route:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.when('/logout', {
templateUrl: 'templates/login.html',
controller: 'LogoutCtrl'
})
.otherwise({
redirectTo: '/'
});
});

Now our routes are in place, we need to implement the three controllers we will need. However, as two of these controllers deal with authentication, we’ll first create some services to handle that, and they’ll need to be tested. Save this as test/services.spec.js:

'use strict';
describe('Services', function () {
beforeEach(function(){
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
beforeEach(angular.mock.module('mynewanimalfriend.services'));
describe('Token service', function () {
var mockBackend, Token;
beforeEach(inject(function (_Token_, _$httpBackend_) {
Token = _Token_;
mockBackend = _$httpBackend_;
}));
it('can create a new token', function () {
mockBackend.expectPOST('http://localhost:8000/api/authenticate', '{"email":"bob@example.com","password":"password"}').respond({token: 'mytoken'});
var token = new Token({
email: 'bob@example.com',
password: 'password'
});
token.$save(function (response) {
expect(response).toEqualData({token: 'mytoken'});
});
mockBackend.flush();
});
});
});

In this test we use the $httpBackend facility from ngMock to mock out our API endpoints. We already have a REST API capable of generating a token, and we set this test up to behave similarly. We specify that it should expect to receive a certain POST request, and should respond with the token mytoken. Run the test to make sure it fails, then save this as js/services.js:

'use strict';
require('angular');
require("angular-resource");
angular.module('mynewanimalfriend.services', ['ngResource'])
.factory('Token', function ($resource) {
return $resource('http://localhost:8000/api/authenticate/');
});

A little explanation is called for. In Angular, the $resource dependency represents an HTTP resource. By default it supports making HTTP requests to the denoted endpoint via GET, POST and DELETE, and it’s trivial to add support for PUT or PATCH methods. Using $resource, you can easily interface with a RESTful web service, and it’s one of my favourite things about Angular.

We also need to load services.js in our main.js file:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
require('./services');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial',
'mynewanimalfriend.services'
])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.when('/logout', {
templateUrl: 'templates/login.html',
controller: 'LogoutCtrl'
})
.otherwise({
redirectTo: '/'
});
});

Now, running the tests should show that they pass.

With that in place, we will also create an authentication service that lets the app determine if the user is logged in. Add this to test/services.spec.js:

describe('Auth service', function () {
var Auth;
beforeEach(inject(function (_Auth_) {
Auth = _Auth_;
}));
it('can set user', function () {
Auth.setUser('mytoken');
var token = localStorage.getItem('authHeader');
expect(token).toEqual('Bearer mytoken');
});
it('can return login status', function () {
localStorage.setItem('authHeader', 'Bearer mytoken');
expect(Auth.isLoggedIn()).toBeTruthy();
});
it('can log the user out', function () {
localStorage.setItem('authHeader', 'Bearer mytoken');
Auth.logUserOut();
expect(Auth.isLoggedIn()).toBeFalsy();
expect(localStorage.getItem('authHeader')).toBeFalsy();
});
});

This service is expected to do three things:

  • Set the current user’s details in local storage
  • Return whether the user is logged in
  • Log the user out

Make sure the test fails, then amend js/services.js as follows:

'use strict';
require('angular');
require("angular-resource");
angular.module('mynewanimalfriend.services', ['ngResource'])
.factory('Auth', function(){
return{
setUser : function (aUser) {
localStorage.setItem('authHeader', 'Bearer ' + aUser);
},
isLoggedIn: function () {
var user = localStorage.getItem('authHeader');
return(user)? user : false;
},
logUserOut: function () {
localStorage.removeItem('authHeader');
}
}
})
.factory('Token', function ($resource) {
return $resource('http://localhost:8000/api/authenticate/');
});

When the user is set, we store the authentication details we need in local storage. We can then use that to determine if they are logged in. When they log out, we simply clear local storage,

That should be enough to make these tests pass. Now we can move on to our controllers. We’ll do the login controller first. Save this as test/controllers.spec.js:

'use strict';
describe('Controllers', function () {
beforeEach(function(){
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
beforeEach(angular.mock.module('mynewanimalfriend.controllers'));
describe('Login Controller', function () {
var mockBackend, scope;
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
mockBackend = _$httpBackend_;
scope = $rootScope.$new();
$controller('LoginCtrl', {
$scope: scope
});
}));
// Test controller scope is defined
it('should define the scope', function () {
expect(scope).toBeDefined();
});
// Test doLogin is defined
it('should define the login method', function () {
expect(scope.doLogin).toBeDefined();
});
// Test doLogin works
it('should allow the user to log in', function () {
// Mock the backend
mockBackend.expectPOST('http://localhost:8000/api/authenticate', '{"email":"user@example.com","password":"password"}').respond({token: 123});
// Define login data
scope.credentials = {
email: 'user@example.com',
password: 'password'
};
// Submit the request
scope.doLogin();
// Flush the backend
mockBackend.flush();
// Check login complete
expect(localStorage.getItem('authHeader')).toEqual('Bearer 123');
});
});
});

We check that the scope and the doLogin() method are defined. We then mock the backend’s /api/authenticate route to respond with a dummy token when our credentials are provided. Then, we set the credentials in the variable $scope.credentials, call doLogin(), flush the backend, and check the authentication header has been set.

Once you’ve verified these tests fail, we can start making them pass. Save this as js/controllers.js:

'use strict';
require('angular');
require('angular-route');
require('./services');
angular.module('mynewanimalfriend.controllers', [
'mynewanimalfriend.services',
"ngMaterial"
])
.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
$scope.doLogin = function () {
var token = new Token($scope.credentials);
token.$save(function (response) {
if (response.token) {
// Set up auth service
Auth.setUser(response.token);
// Redirect
$location.path('/');
}
}, function (err) {
alert('Unable to log in - please check your details are correct');
});
};
});

The LoginCtrl controller accepts the scope, location, and our two services. When doLogin() is alled, it picks up the values in $scope.credentials, which we will set in our template later. It then makes a POST request to our endpoint including those credentials. Our API backend should return the new token in the response, and the token is stored using the Auth service. Otherwise, it raises an error.

Check the test now passes before moving onto the logout functionality. Add this to test/controllers.spec.js:

describe('Logout Controller', function () {
var scope;
beforeEach(inject(function ($rootScope, $controller, Auth) {
Auth.setUser('Blah');
scope = $rootScope.$new();
$controller('LogoutCtrl', {
$scope: scope
});
}));
// Test controller scope is defined
it('should define the scope', function () {
expect(scope).toBeDefined();
});
// Test session cleared
it('should clear the session', function () {
expect(localStorage.getItem('authHeader')).toEqual(null);
});
});

We want to ensure that when the user navigates to the route managed by the LogoutCtrl controller, the session is cleared, so we set up an existing session, call the controller, check it’s defined, and then check that local storage is empty.

Once you’ve verified that the test fails, amend the controllers as follows:

'use strict';
require('angular');
require('angular-route');
require('./services');
angular.module('mynewanimalfriend.controllers', [
'mynewanimalfriend.services',
"ngMaterial"
])
.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
$scope.doLogin = function () {
var token = new Token($scope.credentials);
token.$save(function (response) {
if (response.token) {
// Set up auth service
Auth.setUser(response.token);
// Redirect
$location.path('/');
}
}, function (err) {
alert('Unable to log in - please check your details are correct');
});
};
})
.controller('LogoutCtrl', function ($scope, $location, Auth) {
// Log user out
Auth.logUserOut();
// Redirect to login page
$location.path('/login');
});

Our LogoutCtrl controller is very simple - it just logs the user out and redirects them back to the login form. Our final controller is for the home page:

describe('Home Controller', function () {
var scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
$controller('HomeCtrl', {
$scope: scope
});
}));
// Test controller scope is defined
it('should define the scope', function () {
expect(scope).toBeDefined();
});
});

For now our home controller does nothing except define the scope, so it’s easy to implement:

'use strict';
require('angular');
require('angular-route');
require('./services');
angular.module('mynewanimalfriend.controllers', [
'mynewanimalfriend.services',
"ngMaterial"
])
.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
$scope.doLogin = function () {
var token = new Token($scope.credentials);
token.$save(function (response) {
if (response.token) {
// Set up auth service
Auth.setUser(response.token);
// Redirect
$location.path('/');
}
}, function (err) {
alert('Unable to log in - please check your details are correct');
});
};
})
.controller('LogoutCtrl', function ($scope, $location, Auth) {
// Log user out
Auth.logUserOut();
// Redirect to login page
$location.path('/login');
})
.controller('HomeCtrl', function ($scope) {
});

Verify that the tests pass, and our controllers are done for now. However, we still have some work to do to hook the various elements up. First, of all, our main.js unnecessarily loads our services - since we only use those services in our controllers, we don’t need them there. We also need to be able to keep users out of routes other than login when not logged in. Here’s what you main.js should look like:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
require('./controllers');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial',
'mynewanimalfriend.controllers'
])
.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
if ($location.path() !== '/login') {
$location.path('/login');
}
}
});
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('sessionInjector');
$httpProvider.interceptors.push('authInterceptor');
}])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.when('/logout', {
templateUrl: 'templates/login.html',
controller: 'LogoutCtrl'
})
.otherwise({
redirectTo: '/'
});
});

Note that we set it up to intercept the HTTP request with the session injector and the auth interceptor. Next we need to create these in js/services.js:

'use strict';
require('angular');
require("angular-resource");
angular.module('mynewanimalfriend.services', ['ngResource'])
.factory('Auth', function(){
return{
setUser : function (aUser) {
localStorage.setItem('authHeader', 'Bearer ' + aUser);
},
isLoggedIn: function () {
var user = localStorage.getItem('authHeader');
return(user)? user : false;
},
logUserOut: function () {
localStorage.removeItem('authHeader');
}
}
})
.factory('Token', function ($resource) {
return $resource('http://localhost:8000/api/authenticate/');
})
.factory('sessionInjector', function (Auth) {
var sessionInjector = {
request: function (config) {
if (Auth.isLoggedIn()) {
config.headers.Authorization = Auth.isLoggedIn();
}
return config;
}
};
return sessionInjector;
})
.service('authInterceptor', function ($q, Auth, $location) {
var service = this;
service.responseError = function (response) {
if (response.status == 400) {
Auth.logUserOut();
$location.path('/login');
}
return $q.reject(response);
};
});

I’ll walk you through these. sessionInjector adds the authorization HTTP header to every request to the server if the user is logged in, so that it returns the right user’s details. authInterceptor catches any 400 errors, denoting that the user is not authenticated with a current JSON web token, and logs the user out. In this way we can handle the expiry of a user’s token.

Now the logic of our app is in place, but that’s no use without some content…

Angular templating

We have one very basic HTML template, but that’s just a boilerplate for inserting the rest of our content. For the rest of the HTML we’ll need to load templates dynamically, and we’ll use Angular Material to help us build a nice UI quickly. Run the following commands to create the files:

$ mkdir www/templates
$ touch www/templates/login.html
$ touch www/templates/home.html

We need to import the CSS for Angular Material. Add this to sass/style.scss:

// Angular Material
@import "node_modules/angular-material/angular-material.scss";

With that done, we need to configure theming in main.js:

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
require('angular-material');
require('./controllers');
angular.module('mynewanimalfriend', [
'ngRoute',
'ngAnimate',
'ngMaterial',
'mynewanimalfriend.controllers'
])
.config(function ($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('purple')
.accentPalette('cyan');
})
.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
if ($location.path() !== '/login') {
$location.path('/login');
}
}
});
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('sessionInjector');
$httpProvider.interceptors.push('authInterceptor');
}])
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
})
.when('/logout', {
templateUrl: 'templates/login.html',
controller: 'LogoutCtrl'
})
.otherwise({
redirectTo: '/'
});
});

You may want to look at the documentation for Angular Material to choose your own theme options. Next, let’s create our login template at www/templates/login.html:

<md-content md-theme="default" layout-gt-sm="row" layout-padding>
<div>
<md-input-container class="md-block">
<label>Email</label>
<input ng-model="credentials.email" type="email">
</md-input-container>
<md-input-container class="md-block">
<label>Password</label>
<input ng-model="credentials.password" type="password">
</md-input-container>
<md-button class="md-raised md-primary" ng-click="doLogin()">Submit</md-button>
</div>
</md-content>

We’re using Angular Material’s input and button directives to make our inputs look a bit nicer. Note that the ng-click handler calls the doLogin() method of our controller, and that the ng-model attributes contain the credentials object that gets passed to the API. If you haven’t used Angular before, ng-model essentially lets you bind a variable to an element’s value so, for instance, when an input is changed, it can be easily accessed via the variable.

Next, we’ll implement a placeholder for our home page with a log out button. Save this as www/templates/home.html:

<md-toolbar>
<div class="md-toolbar-tools">
<md-button aria-label="Log out" href="#logout">
Log out
</md-button>
</div>
</md-toolbar>

That should be all we need to demonstrate logging in and out of our app. Let’s try it out. First run the Gulp task to show the app in the browser:

$ gulp

Then, in another shell session, switch to the directory with the backend and run the server for that:

$ php artisan serve

You should already have a user account set up and ready to use thanks to the seeder we wrote. The browser should show the login page by default, and if you fill in the login form and click the button you should see the home page. You should then be able to log out again.

Congratulations! We’ve got authentication working.

Switching to HTML5 routing

You may note that the URLs use hashes - they are in the format http://localhost:5000/#/login. Wouldn’t it be better if we didn’t use the hash? Fortunately modern browsers support this via the HTML5 pushState API, and Angular has built-in support for this.

To enable it, we first need to declare a base URL in www/index.html. Amend it as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
<title>My New Animal Friend</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<base href="/">
</head>
<body>
<div>
<div ng-app="mynewanimalfriend" ng-cloak>
<div ng-view></div>
</div>
</div>
</body>
<script language="javascript" type="text/javascript" src="/js/bundle.js"></script>
</html>

Here we’ve added the <base href="/"> tag to denote our base URL. Next we configure Angular to use HTML5 routing in main.js:

.config(function($locationProvider) {
$locationProvider.html5Mode(true);
})

And amend the URL in the home template:

<md-toolbar>
<div class="md-toolbar-tools">
<md-button aria-label="Log out" href="/logout">
Log out
</md-button>
</div>
</md-toolbar>

Now, we should be using HTML5 routing throughout.

With that done, we can finish for today. We’ve got our basic app skeleton and authentication system up and running, and we’ll be in a good place to continue developing the rest of the app next time. I’ve put the source code on Github, and you can find this lesson’s work under the lesson-2 tag.

Next time we’ll develop the app further, including implementing the pet search functionality.

Recent Posts

Enforcing a Coding Standard With PHP Codesniffer

Decorating Laravel Repositories

My First Laravel Package

Integrating Behat With Laravel

Testing Laravel Middleware

About me

I'm a web and mobile app developer based in Norfolk. My skillset includes Python, PHP and Javascript, and I have extensive experience working with CodeIgniter, Laravel, Django, Phonegap and Angular.js.