uri*_*ium 5 unit-testing jasmine angularjs
这可能是重复的,但我在这里看了很多其他问题,他们通常会以某种方式错过我正在寻找的东西.他们主要谈论他们自己创造的服务.我能做到并做到了.我试图覆盖我的模拟注入的角度.我认为它会是相同的,但由于某些原因,当我单步执行代码时,它始终是角度$ cookieStore而不是我的模拟.
我对jasmine和angularjs的经验非常有限.我来自C#背景.我经常编写单元测试moq(C#的模拟框架).我习惯看到这样的事情
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想模拟我在我的一个控制器中使用的$ cookieStore服务.
app.controller('PageController', ['$scope', '$cookieStore', function($scope, $cookieStore) {
$scope.cars = $cookieStore.get('cars');
if($scope.cars == 0) {
// Do other logic here
.
}
$scope.foo = function() {
.
.
}
}]);
Run Code Online (Sandbox Code Playgroud)
我想确保使用'garage'参数调用$ cookieStore.get方法.我也希望能够控制它的回馈.我希望它返回0然后我的控制器必须做一些其他逻辑.
这是我的测试.
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');
});
});
Run Code Online (Sandbox Code Playgroud)
这是我之前回答中讨论的解决方案.
在我的控制器中,我使用$ 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);
});
Run Code Online (Sandbox Code Playgroud)
我没有在$ controller中注入任何东西.它刚刚起作用.看看日志:
日志:'###使用位置集'
日志:'###设置位置:/ test'
日志:'###使用位置搜索模拟'
日志:'###设置搜索位置:{"限制":"50","q":"ani","tags":[1,2],"category_id":5}'
| 归档时间: |
|
| 查看次数: |
5952 次 |
| 最近记录: |