Skip to content

Commit

Permalink
test(localStorageSpec): test serialization numbers , issue #99
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m committed Oct 6, 2014
1 parent fd2fc27 commit 44575f4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/angular-local-storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ angularLocalStorage.provider('localStorageService', function() {
// Let's convert undefined values to null to get the value consistent
if (typeof value === "undefined") {
value = null;
} else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(value)) {
} else if (angular.isObject(value) || angular.isArray(value) || angular.isNumber(+value || value)) {
value = angular.toJson(value);
}

Expand Down Expand Up @@ -168,13 +168,19 @@ angularLocalStorage.provider('localStorageService', function() {
return null;
}

if (item.charAt(0) === "{" || item.charAt(0) === "[" || angular.isNumber(+item || item)) {
if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) {
return angular.fromJson(item);
}

return item;
};

// Test if string is only contains numbers
// e.g '1' => true, "'1'" => true
function isStringNumber(num) {
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
}

// Remove an item from local storage
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
var removeFromLocalStorage = function (key) {
Expand Down
32 changes: 32 additions & 0 deletions test/spec/localStorageSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,38 @@ describe('localStorageService', function() {
);
});

it('should be able to set and get integers', function() {
inject(
addItem('key', 777),
expectAdding('ls.key', angular.toJson(777)),
expectMatching('key', 777)
);
});

it('should be able to set and get float numbers', function() {
inject(
addItem('key', 123.123),
expectAdding('ls.key', angular.toJson(123.123)),
expectMatching('key', 123.123)
);
});

it('should be able to set and get strings', function() {
inject(
addItem('key', 'string'),
expectAdding('ls.key', 'string'),
expectMatching('key', 'string')
);
});

it('should be able to set and get numbers as a strings', function() {
inject(
addItem('key', '777'),
expectAdding('ls.key', angular.toJson('777')),
expectMatching('key', '777')
)
});

it('should be able to get items', inject(
getItem('key'),
expectGetting('ls.key')
Expand Down

0 comments on commit 44575f4

Please sign in to comment.