我有一个简单的服务,我正在尝试编写单元测试:
angular
.module('myapp.core.services')
.service('searchService', function(api) {
'use strict';
this.getFilterState = function(){
return (sessionStorage.filterState != "undefined" ? angular.fromJson( sessionStorage.filterState ) : {} )
}
this.setFilterState = function(filterState){
sessionStorage.filterState = angular.toJson(filterState);
}
});
这是单元测试:
/**
* Tests for searchService service
*/
describe('searchService service', function() {
var rootScope, svc;
beforeEach(module('myapp.core.services'));
beforeEach( inject(function($window, $rootScope, searchService) {
rootScope = $rootScope;
svc = searchService;
}));
it('should contain a searchService', function(){
expect(svc).toBeDefined();
});
it('should return an empty object when called the first time',function(){
console.log(svc);
expect(svc.getFilterState()).toEqual({});
});
});
当我运行测试时,expect(svc).toBeDefined();
评估为true,但expect(svc.getFilterState()).toEqual({});
会抛出错误。
错误日志:
Chrome 34.0.1847 (Mac OS X 10.8.4) LOG: {getFilterState: function (){ ... }, setFilterState: function (filterState){ ... }}
Chrome 34.0.1847 (Mac OS X 10.8.4) searchService service should return an empty object when called the first time FAILED
Expected undefined to equal { }.
Error: Expected undefined to equal { }.
at null.<anonymous> (/myapp/assets/js/tests/core/services/searchService.js:20:38)
..................
PhantomJS 1.9.7 (Mac OS X) LOG: {getFilterState: function () { ... }, setFilterState: function (filterState) { ... }}
PhantomJS 1.9.7 (Mac OS X) searchService service should return an empty object when called the first time FAILED
Expected undefined to equal { }.
我还运行了返回undefined
的console.log(svc.getFilterState()),所以我有点失落。
以下是我所依据的测试(有效):
/**
* Tests for userPromise service
*/
describe('userPromise service', function() {
var httpBackend, rootScope, svc;
beforeEach(function(){
module('myapp.core.services');
inject(function($window, $rootScope, $httpBackend, userPromise) {
httpBackend = $httpBackend;
rootScope = $rootScope;
svc = userPromise;
});
});
it('should make a request to API', function() {
httpBackend.expectGET('/api/v1/users/current').respond({a: 'b'});
svc.then(function(v){
expect(v.a).toEqual('b');
},function(){
// AAAAAAAAAAAA
expect(false).toBe(true);
});
httpBackend.flush();
});
it('should return cached userPromise', function() {
httpBackend.expectGET('/api/v1/users/current').respond({a: 'b'});
httpBackend.flush();
svc.then(function(v){
expect(v.a).toEqual('b');
},function(){
// AAAAAAAAAAAA
expect(false).toBe(true);
});
});
it('should reject in case of failure', function() {
httpBackend.expectGET('/api/v1/users/current').respond(500);
svc.then(function(){
// AAAAAAAAAAAA
expect(false).toBe(true);
},function(){
expect(true).toBe(true);
});
httpBackend.flush();
});
});