【发布时间】:2015-11-23 19:02:25
【问题描述】:
我正在使用 Karma、Mocha、Sinon 和 Chai 进行 Angular 单元测试,我正在尝试弄清楚如何使用 $location 在控制器中模拟重定向。
我的控制器执行以下重定向:
$location.path('home');
我想尝试使用间谍来模拟重定向,这就是我目前正在做的事情:
describe('Auth Controller', function() {
var controller;
var $location;
beforeEach(function() {
bard.appModule('app.auth');
bard.inject('$controller', '$rootScope', '$location');
});
beforeEach(function() {
$location = {
path: sinon.spy().returned('Fake location')
};
controller = $controller('authCtrl', { $scope: $rootScope, $location: $location });
});
it('should take you to the metrics page on successful login', function() {
expect($location.path).to.have.been.calledWith("Fake location");
});
});
我收到以下错误:
TypeError: false is not a spy or call to a spy!
我不确定如何正确地模拟这个,或者我什至是否以正确的方式处理这个。
感谢单元测试专家的任何帮助。提前致谢!
【问题讨论】:
-
为什么需要模拟 $location?通常我不会嘲笑它,我只是像这样使用 expect(location.path()).toBe('/myPage');
-
你这样做有什么特别的原因吗?我认为这个想法是模拟 $location 服务。
-
没有什么特别的原因,对我来说这是测试重定向行为的最简单方法
-
@RafaelZeffa 所以我正在尝试这个:
expect($location.path()).to.equal('login');但我收到了这个错误:TypeError: Cannot read property 'path' of undefined。
标签: angularjs unit-testing sinon chai karma-mocha