Skip to content

Commit

Permalink
fix: improve confused error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
thebiltheory committed May 2, 2020
1 parent e4d3dc2 commit c7a3ead
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion example/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import useBreakpoints from 'usebreakpoints'
const App = () => {
const breakpoints = [576, 768, 992, 1200]

const stringBreakpoints = ['576px', '768lol', '992px', '1200px']
const stringBreakpoints = ['576px', '768px', '992px', '1200px']

const [value, breakpoint] = useBreakpoints([1, 2, 3, 4], breakpoints)

Expand Down
7 changes: 7 additions & 0 deletions src/utils/__tests__/isValidUnit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ describe('Validates breakpoint strings with units', () => {
)
})

it('Should throw an error if an invalid CSS unit is provided', () => {
expect(() => isValidUnit('1000')).toThrowError(`
Breakpoint "1000" does not have a valid length unit.
Did you mean to add cm | mm | in | px | pt | pc | em | ex | ch | rem | vw | vh | vmin | vmax | % ?
`)
})

it('Should return true if a valid CSS is provided', () => {
expect(() => isValidUnit('1000px')).toBeTruthy()
})
Expand Down
13 changes: 13 additions & 0 deletions src/utils/isValidUnit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,22 @@ const units: string[] = [
'vmax',
'%'
]

export default function isValidUnit(breakpoint: string) {
const unit: string[] = breakpoint.match(/(\D+)/g) || ['']

/**
* @todo: Customize the Erro output
* to point to the right file and file number
* in the stack trace
*/
if (unit[0] === '') {
throw new Error(`
Breakpoint "${breakpoint}" does not have a valid length unit.
Did you mean to add ${units.join(' | ')} ?
`)
}

if (!units.includes(unit[0])) {
throw new Error(`"${unit}" is not a valid CSS unit.`)
}
Expand Down

0 comments on commit c7a3ead

Please sign in to comment.