5

This may be a duplicate but I have looked at a lot of other questions here and they usually miss what I am looking for in some way. They mostly talk about a service they created themselves. That I can do and have done. I am trying to override what angular is injecting with my mock. I thought it would be the same but for some reason when I step through the code it is always the angular $cookieStore and not my mock.

I have very limited experience with jasmine and angularjs. I come from a C# background. I usually write unit tests moq (mocking framework for C#). I am use to seeing something like this

[TestClass]
public PageControllerTests
{
    private Mock<ICookieStore> mockCookieStore;
    private PageController controller;

    [TestInitialize]
    public void SetUp()
    {
        mockCookieStore = new Mock<ICookieStore>();
        controller = new PageController(mockCookieStore.Object);
    }

    [TestMethod]
    public void GetsCarsFromCookieStore()
    {
        // Arrange
        mockCookieStore.Setup(cs => cs.Get("cars"))
                    .Return(0);

        // Act
        controller.SomeMethod();

        // Assert
        mockCookieStore.VerifyAll();
    }
}

I want mock the $cookieStore service which I use in one of my controllers.

app.controller('PageController', ['$scope', '$cookieStore', function($scope, $cookieStore) {

    $scope.cars = $cookieStore.get('cars');

    if($scope.cars == 0) {
            // Do other logic here
            .
    }

    $scope.foo = function() {
        .
        .
    }
}]);

I want to make sure that the $cookieStore.get method is invoked with a 'garage' argument. I also want to be able to control what it gives back. I want it to give back 0 and then my controller must do some other logic.

Here is my test.

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

    var controller,
        scope,
        cookieStoreSpy;

    beforeEach(function () {
        cookieStoreSpy = jasmine.createSpyObj('CookieStore', ['get']);
        cookieStoreSpy.get.andReturn(function(key) {
            switch (key) {
                case 'cars':
                    return 0;
                case 'bikes':
                    return 1;
                case 'garage':
                    return { cars: 0, bikes: 1 };
            }
        });

        module(function($provide) {
            $provide.value('$cookieStore', cookieStoreSpy);
        });
        module('App');

    });

    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
        scope = $rootScope.$new();
        controller = $controller;
    }));

    it('Gets car from cookie', function () {
        controller('PageController', { $scope: scope });
        expect(cookieStoreSpy.get).toHaveBeenCalledWith('cars');
    });
});
4

4 回答 4

5

这是我们在之前的回答中讨论的解决方案。

在我的控制器中,我使用 $location.path 和 $location.search。所以用我的模拟覆盖 $location 我做了:

locationMock = jasmine.createSpyObj('location', ['path', 'search']);
locationMock.location = "";

locationMock.path.andCallFake(function(path) {
  console.log("### Using location set");
  if (typeof path != "undefined") {
    console.log("### Setting location: " + path);
    this.location = path;
  }

  return this.location;
});

locationMock.search.andCallFake(function(query) {
  console.log("### Using location search mock");
  if (typeof query != "undefined") {
    console.log("### Setting search location: " + JSON.stringify(query));
    this.location = JSON.stringify(query);
  }

  return this.location;
});

module(function($provide) {
  $provide.value('$location', locationMock);
});

我不必在 $controller 中注入任何东西。它刚刚奏效。查看日志:

LOG: '### 使用位置集'

LOG: '### 设置位置:/test'

LOG: '### 使用位置搜索模拟'

LOG: '### 设置搜索位置:{"limit":"50","q":"ani","tags":[1,2],"category_id":5}'

于 2013-10-02T10:54:32.360 回答
0

如果要检查参数,请监视方法

// declare the cookieStoreMock globally
var cookieStoreMock;

beforeEach(function() {
  cookieStoreMock = {};

  cookieStoreMock.get = jasmine.createSpy("cookieStore.get() spy").andCallFake(function(key) {
    switch (key) {
      case 'cars':
        return 0;
      case 'bikes':
        return 1;
      case 'garage':
        return {
          cars: 0,
          bikes: 1
        };
    }
  });

  module(function($provide) {
    $provide.value('cookieStore', cookieStoreMock);
  });
});

然后测试参数做

expect(searchServiceMock.search).toHaveBeenCalledWith('cars');
于 2013-10-02T08:49:51.777 回答
0

这是一个示例https://github.com/lucassus/angular-seed/blob/81d820d06e1d00d3bae34b456c0655baa79e51f2/test/unit/controllers/products/index_ctrl_spec.coffee#L3它是带有 mocha + sinon.js 的咖啡脚本代码,但想法是一样的.

基本上使用以下代码片段,您可以加载模块并替换其服务:

beforeEach(module("myModule", function($provide) {
  var stub = xxx; //... create a stub here
  $provide.value("myService", stub);
}));

稍后在规范中,您可以注入此存根服务并进行断言:

it("does something magical", inject(function(myService) {
  subject.foo();
  expect(myService).toHaveBeenCalledWith("bar");
}));

您可以在这篇出色的博客文章中找到有关模拟和测试的更多详细信息和提示:http ://www.yearofmoo.com/2013/09/advanced-testing-and-debugging-in-angularjs.html

于 2013-10-02T08:53:50.130 回答
0

为什么要模拟 cookieStore,你可以直接使用它而无需修改?下面的代码是控制器的部分单元测试,它使用 $cookieStore 来放置和获取 cookie。如果您的控制器有一个称为“setACookie”的方法,它使用 $cookieStore.put('cookieName', cookieValue) ... 那么测试应该能够读取设置的值。

describe('My controller', function() {
   var $cookieStore;
   describe('MySpecificController', function() {

    beforeEach(inject(function(_$httpBackend_, $controller, _$cookieStore_) {
        $cookieStore = _$cookieStore_;
        // [...] unrelated to cookieStore
    }));

    it('should be able to reference cookies now', function () {
       scope.setACookie();
       expect($cookieStore.get('myCookieName')).toBe('setToSomething');
    });

 });
于 2014-02-28T16:48:26.673 回答