我是AngularJS单元测试的新手。我想用茉莉花在控制器中测试一个函数。在同一个控制器中还有一个$ locationChangeStart手表
$scope.$on('$locationChangeStart', function(){
$scope.killTimer($scope.timer);
});
我不想要测试这个,但另一个功能。当我尝试运行测试时,我收到一个错误,指向$ scope。$ on line:
TypeError: undefined is not a function
我该怎么做才能让测试不在这条线上?我复制了我的测试规范,因为我不确定那里的一切是否正常。
describe('invoiceListController', function() {
beforeEach(module('invoice'));
var $controller;
beforeEach(inject(function(_$controller_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('invoiceList', { $scope: $scope });
});
describe('deleteInvoices()', function(){
it('should do nothing when no invoice is selected', function() {
$scope.invoicesToDelete = false;
var response = $scope.deleteInvoices();
expect(response).toEqual(false);
});
});
});
我要测试的代码:
$scope.deleteInvoices = function(){
if($scope.invoicesToDelete) {
return true;
} else {
return false;
}
};
Plunker中的示例:Plunker
答案 0 :(得分:0)
您当前的测试目前不会实际通过作用域,因为您需要在设置和运行作用域函数后应用$ apply。这不会解决您的未定义问题,请检查您编写的函数是否可用于您的测试($ scope.killTimer)。可能是因为它会在killTimer函数中出现错误。
即
it('should do nothing when no invoice is selected', function() {
$scope.invoicesToDelete = false;
var response = $scope.deleteInvoices();
$scope.$apply();
expect(response).toEqual(false);
});
<强>更新强> 在查看了你的plunkr之后,实际上你的测试中的范围实现是错误的,通过修复这个整个测试用例按预期工作。
$scope = $rootScope.$new();
您应该注入控制器以正确实施范围。我在这里更新了你的plunker。 http://plnkr.co/edit/p3LShkxT12B1qw7fNbEb?p=preview