Skip to content

Commit

Permalink
fix(shared): support custom .toString() in text interpolation again (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
catrope authored Jul 29, 2021
1 parent 1e3d468 commit 9d5fd33
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
14 changes: 13 additions & 1 deletion packages/shared/__tests__/toDisplayString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,22 @@ describe('toDisplayString', () => {
})
).toBe(JSON.stringify({ n: 1, np: 2 }, null, 2))
})

test('objects with custom toString', () => {
class TestClass {
toString() {
return 'foo'
}
}
const instance = new TestClass()
expect(toDisplayString(instance)).toBe('foo')
const obj = { toString: () => 'bar' }
expect(toDisplayString(obj)).toBe('bar')
})

test('native objects', () => {
const div = document.createElement('div')
expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)
expect(toDisplayString(div)).toBe('[object HTMLDivElement]')
expect(toDisplayString({ div })).toMatchInlineSnapshot(`
"{
\\"div\\": \\"[object HTMLDivElement]\\"
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/toDisplayString.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
import {
isArray,
isMap,
isObject,
isPlainObject,
isSet,
objectToString
} from './index'

/**
* For converting {{ interpolation }} values to displayed strings.
Expand All @@ -7,7 +14,7 @@ import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
export const toDisplayString = (val: unknown): string => {
return val == null
? ''
: isObject(val)
: isArray(val) || (isObject(val) && val.toString === objectToString)
? JSON.stringify(val, replacer, 2)
: String(val)
}
Expand Down

0 comments on commit 9d5fd33

Please sign in to comment.