Skip to content

Commit af853a5

Browse files
authored
Merge pull request #45 from Goodwine/main
Ensure that `truncate()` always returns a string as documented.
2 parents 080b72d + f3cde4d commit af853a5

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

src/truncate.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,20 +96,20 @@ const defaultOptions: IOptions = {
9696
// an special object to store user's default options, keep the defaultOptions clean
9797
let userDefaults: IOptions = defaultOptions
9898

99-
export default function truncate(html: string | CheerioAPI, length?: number | IOptions, truncateOptions?: IOptions) {
99+
export default function truncate(html: string | CheerioAPI, length?: number | IOptions, truncateOptions?: IOptions): string {
100100
const options = sanitizeOptions(length, truncateOptions)
101101

102102
if (!html ||
103103
isNaN(options.length) ||
104104
options.length < 1 ||
105105
options.length === Infinity) {
106-
return html
106+
return isCheerioInstance(html) ? html.html() ?? '' : html;
107107
}
108108

109109
let $: CheerioAPI
110110

111111
if (isCheerioInstance(html)) {
112-
$ = html as CheerioAPI
112+
$ = html
113113
} else {
114114
// Add a wrapper for text node without tag like:
115115
// <p>Lorem ipsum <p>dolor sit => <div><p>Lorem ipsum <p>dolor sit</div>
@@ -167,7 +167,7 @@ export default function truncate(html: string | CheerioAPI, length?: number | IO
167167
}
168168

169169
travelChildren($html)
170-
return $html.html()
170+
return $html.html() ?? ''
171171
}
172172

173173
truncate.setup = function (options: IOptions) {

test/truncate.spec.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ describe('Truncate html', () => {
1616
})
1717

1818
it('should NOT truncate a string if NO length provided $', () => {
19-
const html = cheerio.load('string')
19+
const html = 'string'
20+
const $ = cheerio.load(html)
2021

21-
expect(truncate(html)).toBe(html)
22+
expect(truncate($)).toBe('<html><head></head><body>string</body></html>')
2223
})
2324

2425
it('should NOT truncate a string if length is less than or equal to zero', () => {
@@ -31,7 +32,7 @@ describe('Truncate html', () => {
3132
const html = 'string'
3233
const $ = cheerio.load(html)
3334

34-
expect(truncate($, 0)).toBe($)
35+
expect(truncate($, 0)).toBe('<html><head></head><body>string</body></html>')
3536
})
3637
})
3738

0 commit comments

Comments
 (0)