Skip to content

Commit

Permalink
fix: wrong validating function within parseTextDecoder()
Browse files Browse the repository at this point in the history
  • Loading branch information
waitingsong committed Jun 11, 2019
1 parent 9d7ac1b commit b7db14e
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/lib/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export function parseTextDecoder(textDecoder?: TextDecoderFn): TextDecoderFn {
? textDecoder
: (typeof TextDecoder === 'function' ? TextDecoder : null)

validateEncoder(Decoder)
validateDecoder(Decoder)
return <TextDecoderFn> Decoder
}

Expand All @@ -55,6 +55,13 @@ export function validateEncoder(input: any): void {
}
}

/** Throw error if input be null */
export function validateDecoder(input: any): void {
if (input === null) {
throw new TypeError(ErrorMsg.textDecoderUndefined)
}
}


/** Whether string contains valid base64 characters */
export function validB64Chars(input: string): boolean {
Expand Down
61 changes: 61 additions & 0 deletions test/30_helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@ import {
} from '@waiting/shared-core'
import * as assert from 'power-assert'
import rewire = require('rewire')
import {
TextDecoder as NodeTextDecoder,
TextEncoder as NodeTextEncoder,
} from 'util'

import { ErrorMsg } from '../src/index'
import {
parseDecodeInputBase64,
parseEncodeInputString,
parseTextDecoder,
parseTextEncoder,
validateEncoder,
} from '../src/lib/helper'

Expand Down Expand Up @@ -74,4 +80,59 @@ describe(filename, () => {
})
})


describe('parseTextEncoder() works', () => {
it('with valid input', () => {
const ret = parseTextEncoder(NodeTextEncoder)
assert(ret === NodeTextEncoder)
})

it('with invalid input', () => {
try {
// @ts-ignore
const ret = parseTextEncoder(null)
// node.js v11+ exports global TextEncoder
if (typeof TextEncoder === 'function') {
assert(true)
}
else {
assert(false, 'Should throw error, but NOT')
}
}
catch (ex) {
assert(
ex.message && ex.message.includes(ErrorMsg.textEncoderUndefined),
ex.message,
)
}
})
})

describe('parseTextDecoder() works', () => {
it('with valid input', () => {
const ret = parseTextDecoder(NodeTextDecoder)
assert(ret === NodeTextDecoder)
})

it('with invalid input', () => {
try {
// @ts-ignore
const ret = parseTextDecoder(null)
// node.js v11+ exports global TextDecoder
if (typeof TextDecoder === 'function') {
assert(true)
}
else {
assert(false, 'Should throw error, but NOT')
}
}
catch (ex) {
assert(
ex.message && ex.message.includes(ErrorMsg.textDecoderUndefined),
ex.message,
)
}
})
})

})

0 comments on commit b7db14e

Please sign in to comment.