fix: add tests and refactor slug utils

pull/36856/head
Oliver Eyton-Williams 2019-09-26 16:27:26 +02:00 committed by mrugesh
parent 9c2f1ffd82
commit 3dc4e5897d
3 changed files with 53 additions and 4 deletions

View File

@ -45,7 +45,8 @@
"test:lint": "echo 'Warning: TODO - Define Linting tests.'",
"test:search-indexing": "jest ./search-indexing",
"test:server": "cd ./api-server && npm test && cd ../",
"test:tools": "jest ./tools"
"test:tools": "jest ./tools",
"test:utils": "jest ./utils/*.js"
},
"devDependencies": {
"@freecodecamp/eslint-config": "^2.0.2",

View File

@ -2,11 +2,11 @@ exports.dasherize = function dasherize(name) {
return ('' + name)
.toLowerCase()
.replace(/\s/g, '-')
.replace(/[^a-z0-9\-.]/gi, '');
.replace(/[^a-z\d\-.]/g, '');
};
exports.nameify = function nameify(str) {
return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '');
return ('' + str).replace(/[^a-z\d\s]/gi, '');
};
exports.unDasherize = function unDasherize(name) {
@ -15,7 +15,7 @@ exports.unDasherize = function unDasherize(name) {
// replace dash with space
.replace(/-/g, ' ')
// strip nonalphanumarics chars except whitespace
.replace(/[^a-zA-Z\d\s]/g, '')
.replace(/[^a-z\d\s]/gi, '')
.trim()
);
};

48
utils/slugs.test.js Normal file
View File

@ -0,0 +1,48 @@
/* global describe expect it */
const slugs = require('./slugs');
describe('dasherize', () => {
const { dasherize } = slugs;
it('returns a string', () => {
expect(dasherize('')).toBe('');
});
it('converts characters to lower case', () => {
expect(dasherize('UPPERCASE')).toBe('uppercase');
});
it('converts spaces to dashes', () => {
expect(dasherize(' the space between ')).toBe(
'--the-space--between----'
);
});
it('removes everything except letters, numbers, - and .', () => {
expect(dasherize('1a!"£$%^*()_+=-.b2')).toBe('1a-.b2');
});
});
describe('nameify', () => {
const { nameify } = slugs;
it('returns a string', () => {
expect(nameify('')).toBe('');
});
it('removes everything except letters, numbers and spaces', () => {
expect(nameify('1A !"£$%^*()_+=-.b 2')).toBe('1A b 2');
});
});
describe('unDasherize', () => {
const { unDasherize } = slugs;
it('returns a string', () => {
expect(unDasherize('')).toBe('');
});
it('converts dashes to spaces', () => {
expect(unDasherize('the-space--between')).toBe('the space between');
});
it('removes everything except letters, numbers and spaces', () => {
expect(unDasherize('1A !"£$%^*()_+=-.b 2')).toBe('1A b 2');
});
it('trims off surrounding whitespace', () => {
expect(unDasherize('--the-space--between----')).toBe('the space between');
});
});