试图测试在回调中设置的变量

时间:2014-06-25 19:21:45

标签: javascript angularjs jasmine karma-jasmine

我正在尝试编写一个简单的茉莉花测试来测试$scope.usersUsers.find的回调中的设置。在我上面的上一次测试中,scope.users未定义,因此测试失败。

如何测试scope.users是否已设置,以便我的测试通过?

控制器

angular.module('web').controller('CardsCtrl',function($scope, $http, Users){

  /**
   * Get all users on page load
   */
  Users.find(function(users) {

    $scope.users = users;
});

用户服务

(function(window, angular, undefined) {'use strict';

var urlBase = "http://localhost:3333/api";

var module = angular.module("services", ['ngResource']);
module.factory(
  "Users",
  ['LoopBackResource', 'LoopBackAuth', '$injector', function(Resource, LoopBackAuth, $injector) {
    var R = Resource(
      urlBase + "/users/:id",
      { 'id': '@id' },
      {
        "find": {
          url: urlBase + "/users",
          method: "GET",
          isArray: true,
        },
      }
  );

  return R;
}]);

规范

describe('CardsCtrl', function() {

  var scope, ctrl, users;

  beforeEach(module('web'));

  beforeEach(inject(function($rootScope, $controller, Users) {
    scope = $rootScope.$new();
    users = Users;
    spyOn(users, 'find');
    ctrl = $controller('CardsCtrl', {$scope: scope, Users: users});
  }));


  describe('the cards controller being instantiated', function() {

    it('should be defined', function() {
      expect(ctrl).toBeDefined();
    });

    it('tracks that the spy was called', function() {
      expect(users.find).toHaveBeenCalled();
    });

    it('fetches user data and assigns it to scope.users', function(done) {
      console.log('users= '+scope.users); // <-- THIS RETURNS UNDEFINED
      expect(scope.users).toBeTruthy();
    });
  });

});

1 个答案:

答案 0 :(得分:1)

您需要在间谍上调用.andCallThrough(),并使用$httpBackend模拟http响应:

describe('CardsCtrl', function() {

    var scope, ctrl, users, httpBackend;

    beforeEach(module('web'));

    beforeEach(inject(function($rootScope, $controller, Users, $httpBackend) {
        scope = $rootScope.$new();
        users = Users;
        spyOn(users, 'find').andCallThrough();
        httpBackend = $httpBackend;
        httpBackend.expectGET(urlBase + '/users').respond(200, ['user1', 'user2']);
        ctrl = $controller('CardsCtrl', {$scope: scope, Users: users});
    }));

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    describe('the cards controller being instantiated', function() {

        ... // other tests

        it('fetches user data and assigns it to scope.users', function(done) {
            httpBackend.flush();
            expect(scope.users).toBeTruthy();
        });
    });

});

模拟$httpBackendngMock服务提供,因此您需要包含angular-mock.js才能运行测试。