Search code examples
gruntjsyeomanyeoman-generator-angular

Running tests with localStorage


i have followed this tutorial from Codelab and yeoman. When implemented right you are using local storage to store the TodoList. I have problems with setting up with my tests, to test if this works. This is what i've got so far:

'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  beforeEach(module('yeoTodoApp'), module('LocalStorageModule'));

  var MainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should add items to the list', function () {
    var beforeLength = scope.todos.length;
    scope.todo = 'Test 1';
    scope.addTodo();
    var afterLength = scope.todos.length;
    expect(afterLength-beforeLength).toBe(1);
  });
it('should add items to the list then remove', function () {
    var beforeLength = scope.todos.length;
    scope.todo = 'Test 1';
    scope.addTodo();
    scope.removeTodo(0);
    var afterLength = scope.todos.length;
    expect(afterLength-beforeLength).toBe(0);
  });

});

The error i get is

line 12 col 68 '$httpBackend' is defined but never used. });

How would i write my unit tests to sit the local storage?


Solution

  • your setup is correct now (after you removed $httpBackend from the arguments list)

    Controller: MainCtrl should add items to the list then remove FAILED
    

    this error is a simple test error, which means that your code somewhere doesnt work as expected (your second test fails)

    i for myself would check todos length, and not the result of a mathematical operation.

    i would write your tests the test like this:

    it('should add items to the list then remove', function () {
      scope.todo = 'Test 1';
      expect(scope.todos.length).toBe(0);
      scope.addTodo();
      expect(scope.todos.length).toBe(1);
      scope.removeTodo(0);
      expect(scope.todos.length).toBe(0);
    });
    

    you use jasmine as a test-tool. jasmine logs on errors exactly which expectation fails, so you should get something like

    expect '1' to be '0'
    

    go from there!