AngularJS:TypeError:undefined不是localstorage的对象

时间:2016-06-06 03:59:24

标签: javascript angularjs angularjs-directive mocking karma-jasmine

我想测试var module = angular.module(‘myModule', ['ngStorage']);
 module.controller(‘MyController’, ['$scope', '$localStorage', function($scope,$localStorage){ $scope.storage = $localStorage; $scope.data = {
 name: “55 Cherry St.“ }; $scope.storage.name = $scope.data.name; }]); 中的值。这是我用来存储这些值的包:https://www.npmjs.com/package/ngstorage

这是我的代码:

Jasmine and Mocha

我想在TypeError: undefined is not an object (evaluating 'expect($localStorage).to.be') (line 14) 中测试上面的代码。我不知道我怎么能,因为它现在给了我这个错误:

describe('my Module', function () {
  var $controller;
  var $scope;
  var element;

  beforeEach(module('myModule'));
  beforeEach(module('ngStorage'));

  beforeEach(function() {
    $scope = {};

    inject(function ($controller, $rootScope, $compile, $localStorage) {
      var $controller = $controller('myController', {$scope: $scope});
    });
  });

  describe('My controller', function () {

    it('should contain a $localStorage service', inject(function(
      $localStorage
    ) {
      expect($localStorage).not.to.equal(null);
    }));
});
});

这是我的测试代码:

require "rails_helper"

RSpec.feature "Users can create new review" do
  scenario "with valid attributes" do

    # Put in a 5 star rating here.

    fill_in "Review", with: "This place is pretty good."
    click_button "Create Review"

    expect(page).to have_content "Review has been created."
  end
end

2 个答案:

答案 0 :(得分:1)

Jasmine没有expect('something').not.to.equal()功能。请改用:

expect($localStorage).not.toBe(null);

此外,在复制错误时myController is not defined。修正使用:

var $controller = $controller('MyController', {$scope: $scope});  // MyController (uppercase)

我认为beforeEach(module('ngStorage'));不是必需的,因为它已经是你模块的依赖。

答案 1 :(得分:0)

你必须为它添加一个变量才能测试它。下面是你需要在代码中做的改进

describe('my Module', function () {
  var $controller;
  var $scope;
  var element;
  var $localStorage;

  beforeEach(module('myModule'));
  beforeEach(module('ngStorage'));

  beforeEach(function() {
    $scope = {};

    inject(function ($controller, $rootScope, $compile, $localStorage) {
      var $controller = $controller('myController', {$scope: $scope, $localStorage: $localStorage});
    });
  });

  describe('My controller', function () {

    it('should contain a $localStorage service', inject(function(
      $localStorage
    ) {
      expect($localStorage).not.to.equal(null);
    }));
});
});

OR

expect(controller.$localStorage).not.to.equal(null); //$localStorage is part of controller now