【问题标题】:How can I write jasmine test for angular controller and service like this?我怎样才能为这样的角度控制器和服务编写茉莉花测试?
【发布时间】:2013-04-28 06:03:12
【问题描述】:

我为此被困了几个小时,这是因为我是 Jasmine 和 Angularjs 的新手。基本上,我有这个控制器。

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";
            }
        });
    });

如何编写 Jasmine 测试来模拟 SomeService 以存根 data 并模拟是否有数据 scope 的长度不应为 0,如果 data 为 [] 则消息应为“请来很快回来”。

'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");
    }));

});

测试没有完成,因为我不知道如何从promise 存根then

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 很抱歉,我目前无法提供更长的答案,但我会将 SomeService.getObjs 存为一个假函数,它会返回一个自定义承诺(使用 $q),即你控制。
  • 非常感谢您的回复,但如果您稍后能给我示例代码。那太好了。
  • 我也尝试过这样做,但我不知道如何存根回调函数参数。

标签: javascript unit-testing angularjs jasmine


【解决方案1】:

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

为此添加另一个beforeEach 语句:

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

被模拟的服务会立即在现有的 promise 回调函数中加载结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2020-08-19
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多