我正在尝试从angularjs控制器测试一个函数。
注射部分:
var $scope, $controller;
beforeEach(module('sigfoxSDISApp'));
beforeEach(inject(function(_$controller_, $rootScope, _$log_, _$translate_, _DeviceService_, _$filter_, _translatableIndexFilter_){
$controller = _$controller_;
$scope = $rootScope.$new();
$controller = $controller('AcquitModalCtrl', {
$scope: $scope,
$log: _$log_,
$translate: _$translate_,
DeviceService: _DeviceService_,
$filter_: _$filter_,
translatableIndexFilter: _translatableIndexFilter_
});
}));
测试:
describe('$scope.getReport', function(){
this.success = 0;
this.errors = 0;
it('returns an object with a type, a title and a report', function(){
var result = $scope.getReport(this.success, this.errors);
expect(result.type).toBeDefined();
expect(result.title).toBeDefined();
expect(result.report).toBeDefined();
});
describe('getting type, report and title when success = 0 and errors = 1', function(){
this.errors = 1;
var result = $scope.getReport(this.success, this.errors);
it('returns a type error', function(){
expect(result.type).toEqual('error');
});
it('returns a report empty string', function(){
expect(result.report).toEqual('');
});
it('returns a title which is not empty string', function(){
expect(result.title).toMatch(/[a-z]/);
});
});
});
第一个'it'功能正常工作。 在'获取类型,报告和标题成功= 0和错误= 1'时,我收到以下错误:“TypeError:无法读取未定义的属性'getReport'”
因此在第一个'it'函数之后不再定义$ scope。我不明白为什么。
嵌套描述块
可以嵌套调用描述,并在任何级别定义规范。这允许将套件组合为功能树。在执行规范之前,Jasmine按顺序执行每个beforeEach函数的树。执行规范后,Jasmine同样会遍历afterEach函数。
答案 0 :(得分:0)
我只需在每个描述中添加beforeEach来更改变量值并执行getReport函数,如下所示:
describe('$scope.getReport', function(){
beforeEach(function(){
this.success = 0;
this.errors = 0;
});
it('returns an object with a type, a title and a report', function(){
var result = $scope.getReport(this.success, this.errors);
expect(result.type).toBeDefined();
expect(result.title).toBeDefined();
expect(result.report).toBeDefined();
});
describe('getting type, report and title when success = 0 and errors = 1', function(){
beforeEach(function(){
this.errors = 1;
this.result = $scope.getReport(this.success, this.errors);
)}
it('returns a type error', function(){
expect(this.result.type).toEqual('error');
});
it('returns a report empty string', function(){
expect(this.result.report).toEqual('');
});
it('returns a title which is not empty string', function(){
expect(this.result.title).toMatch(/[a-z]/);
});
});
});