3

I'm stuck for hours for this and it's because I'm new to Jasmine and Angularjs. Basically, I have this controller.

angular.module('toadlane.controllers', []).
    controller('MainController', function($scope, $http, SomeService) {

        var promise = SomeService.getObjects();

        promise.then(function(data) {
            if(data.length > 0) {
                $scope.objs = data;
            } else {
                $scope.message = "Please come back soon";
            }
        });
    });

How can I write a Jasmine test to mock SomeService to stub out data and simulate if there's data the scope's length should not be 0 and if data is [] the message should be "Please come back soon".

'use strict';

describe('controllers', function () {
    var scope, someService;
    beforeEach(module('services'));
    beforeEach(module('controllers'));
    beforeEach(inject(function (SomeService) {
        someService = SomeService;

        var callback = jasmine.createSpy();
        someService.getObjs().then(callback);
    }));

    it('should return some objs', inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();

        expect($controller('MainController', {$scope: scope, SomeService : someService})).toBeTruthy();

        expect(scope.objs.length).toEqual(2);
    }));

    it('should return no objs', inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();

        expect($controller('MainController', {$scope: scope, SomeService : someService})).toBeTruthy();


        expect(scope.message).toEqual("Please come back soon");
    }));

});

The tests are not finished because I don't know how to stub then from promise

Any help is very appreciated. Thanks.

4

1 回答 1

7

Defers 可以通过使用函数返回带有链式方法的对象的函数来模拟 Promise 来测试。在这种情况下,mockedSomeService.getObjs应该返回一个带有 method 的对象then

为了做到这一点,添加另一个beforeEach语句:

beforeEach(module(function ($provide) {
  $provide.value('SomeService', {
    getObjs: function () {
      return {
        then: function (callback) {
          // mockedResponseData is passed to callback
          callback(mockedResponseData);
        }
      };
    }
  }));

模拟服务将立即在现有的承诺回调函数中加载结果。

于 2013-04-27T22:03:12.097 回答